Jake Burton
Jake Burton

Reputation: 63

Use a string to access a local variable by name

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"         )

Upvotes: 6

Views: 7593

Answers (2)

Phrogz
Phrogz

Reputation: 303500

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
    

Upvotes: 10

Hoang Tran
Hoang Tran

Reputation: 309

I guess you matched a string like "read Door" with /^read (.+)$/. So $1 = "Door" and it raised the above error. If you want to downcase that string, just use:

$1.downcase

Upvotes: 0

Related Questions