Eval and methods

Discussion in 'Ruby' started by John, Sep 15, 2003.

  1. John

    John Guest

    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.
    John, Sep 15, 2003
    #1
    1. Advertising

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

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. Eric Newton
    Replies:
    3
    Views:
    9,347
    Brock Allen
    Apr 4, 2005
  2. DataBinder.Eval and Eval.

    , Jun 16, 2006, in forum: ASP .Net
    Replies:
    1
    Views:
    521
    Karl Seguin [MVP]
    Jun 16, 2006
  3. Alex van der Spek

    eval('07') works, eval('08') fails, why?

    Alex van der Spek, Jan 8, 2009, in forum: Python
    Replies:
    6
    Views:
    1,401
    Bruno Desthuilliers
    Jan 8, 2009
  4. Kenneth McDonald
    Replies:
    5
    Views:
    299
    Kenneth McDonald
    Sep 26, 2008
  5. Liang Wang
    Replies:
    8
    Views:
    123
    Ben Morrow
    Feb 2, 2008
Loading...

Share This Page