Eval and methods

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.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,997
Messages
2,570,241
Members
46,831
Latest member
RusselWill

Latest Threads

Top