Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use a string to access a local variable by name

Tags:

ruby

I'm new to this but I have the following code:

when /^read (.+)$/
   puts "Reading #{$1}:"
   puts $1.description.downcase

I would like to use $1 as a variable that I can call methods on, currently the interpreter returns a "NoMethodError: undefined method 'description' for "Door":String".

Edit:

For example:

door = Item.new( :name => "Door", :description => "a locked door" )
key  = Item.new( :name => "Key",  :description => "a key"         )
like image 665
Jake Burton Avatar asked May 07 '11 11:05

Jake Burton


1 Answers

You need to provide more details of your code setup to get a good answer (or for me to figure out which question this is a duplicate of :). What kind of variables are referenced by $1? Here are some guesses:

  1. If this is actually a method on the same instance, you can invoke this method by:

    # Same as "self.foo" if $1 is "foo"
    self.send($1).description.downcase 
    
  2. If these are instance variables, then:

    # Same as "@foo.description.downcase"
    instance_variable_get(:"@#{$1}").description.downcase
    
  3. If these are local variables, you can't do it directly, and you should change your code to use a Hash:

    objs = {
      'foo' => ...,
      'key' => Item.new( :name => "Key", :description => "a key" )
    }
    objs['jim'] = ...
    case some_str
      when /^read (.+)$/
        puts "Reading #{$1}:"
        puts objs[$1].description.downcase
    end
    
like image 134
Phrogz Avatar answered Oct 11 '22 07:10

Phrogz