Eval and methods

a_method = “to_str”
an_attribute = “color”
[ class def elided ]
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?

Everything in Ruby in accomplished through sending messages to objects. So,
t.f can be written as t.send(“f”). Your toad example can use:

t.send(an_attribute + “=”, “green”)
t.send(a_method)

If you are interested in instance variables only, you can use the
instance_variable_get and instance_variable_set methods as well …

t.instance_variable_get(“@color”) #=> “green”
t.instance_variable_set(“@color”, “purple”)

BTW, Ruby expects your to_s method to return the string instead of printing
it.

···

From: gruby@sysarchitects.com [mailto:gruby@sysarchitects.com]


– Jim Weirich / Compuware
– FWP Capture Services