J
John
How do you do meta type stuff in Ruby? E.g.
a_method = "to_str"
an_attribute = "color"
class Toad
attr_accessor :color
def initialize( c )
self.color = c
end
def to_str
puts "#{@color} toad."
end
end
t = Toad.new("brown")
puts t.color #brown
t.to_str #brown toad.
Now how can I use the a_method and an_attribute variables? I'm used to
UserTalk, where I would just say
t.[an_attribute] = "green"
or
t.[a_method] #in UserTalk, evaluates to t.to_str and is called
Am I supposed to use instance_eval?
t.instance_eval(an_attribute)= "green" #syntax error
I'm especially wondering about this in relation to passing a hash to a
constructor, e.g. t = Toad.new( { "color" => "brown", "size" =>
"large" } and having the keys to the hash become attributes of the
object.
a_method = "to_str"
an_attribute = "color"
class Toad
attr_accessor :color
def initialize( c )
self.color = c
end
def to_str
puts "#{@color} toad."
end
end
t = Toad.new("brown")
puts t.color #brown
t.to_str #brown toad.
Now how can I use the a_method and an_attribute variables? I'm used to
UserTalk, where I would just say
t.[an_attribute] = "green"
or
t.[a_method] #in UserTalk, evaluates to t.to_str and is called
Am I supposed to use instance_eval?
t.instance_eval(an_attribute)= "green" #syntax error
I'm especially wondering about this in relation to passing a hash to a
constructor, e.g. t = Toad.new( { "color" => "brown", "size" =>
"large" } and having the keys to the hash become attributes of the
object.