How can I call a class method in Ruby with the method name stored in an array? -
i working on poker game in ruby. instead of using numerous if-else statements check value of player's hand, decided following:
#calculate players score def score poss.map {|check| if (check[1].call()) @score = check[0] puts @score return check[0] else false end } end poss = [ [10, :royal_flush?], [9, :straight_flush?], [8, :four_kind?], [7, :full_house?], [6, :flush?], [5, :straight?], [4, :three_kind?], [3, :two_pairs?], [2, :pair?] ]
the second item in each item of 'poss' method created check whether player has hand. attempting call method .call(), following error:
player.rb:43:in `block in score': undefined method `call' :royal_flush?:symbol (nomethoderror) player.rb:42:in `map' player.rb:42:in `score' player.rb:102:in `get_score' player.rb:242:in `<main>'
http://ruby-doc.org/core-2.2.2/object.html object#send
method looking for.
since wanting 'class method', object should self when declaring instance methods of class contains 'class methods'
try code
#calculate players score def score poss.map |check| if self.send check[1] @score = check[0] puts @score return check[0] else false end end end poss = [ [10, :royal_flush?], [9, :straight_flush?], [8, :four_kind?], [7, :full_house?], [6, :flush?], [5, :straight?], [4, :three_kind?], [3, :two_pairs?], [2, :pair?] ]
styles vary person person, however, think when using multi line blocks, best use 'do,end' pair instead of '{ }'
https://github.com/bbatsov/ruby-style-guide
i think confusion may come code looks this
foobar = ->(foo,bar){puts "passed in #{foo}, #{bar}"} foobar.call("one","two")
if first line abstracted other parts of program may have thought foobar method, lambda. procs , lambdas methods better.. in own way.. check out article on procs, blocks , lambdas.
http://www.reactive.io/tips/2008/12/21/understanding-ruby-blocks-procs-and-lambdas/
but if interested check out https://www.codecademy.com/forums/ruby-beginner-en-l3zci more detailed hands on pbls
Comments
Post a Comment