[lnkForumImage]
TotalShareware - Download Free Software

Confronta i prezzi di migliaia di prodotti.
Asp Forum
 Home | Login | Register | Search 


 

Forums >

comp.lang.ruby

Eval and methods

gruby

9/15/2003 9:56:00 PM

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.