[lnkForumImage]
TotalShareware - Download Free Software

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


 

Forums >

comp.lang.ruby

Re: Eval and methods

Weirich, James

9/15/2003 10:36:00 PM

From: gruby@sysarchitects.com [mailto:gruby@sysarchitects.com]
> 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.

--
-- Jim Weirich / Compuware
-- FWP Capture Services