this question has answer here:
excuse me example; trying develop independent example present requirement, may appear contrived:
class animal name = 'no name' %w(bark walk).each |action| define_method(action) name + ' ' + action end end end class pig < animal name = 'piggie' end animal.new.walk # => "no name walk" pig.new.walk # => "no name walk" the last line expected return "piggie walk", doesn't. why happen , how make use constant defined in pig?
try this
class animal def initialize @name ||= "no name" end %w(bark walk).each |action| define_method(action) "#{@name} #{action}" end end end class pig < animal def initialize @name = 'piggie' end end animal.new.walk # => "no name walk" pig.new.walk
Comments
Post a Comment