使用字符串按名称访问局部变量

使用字符串按名称访问局部变量

问题描述:

我是新手,但我有以下代码:

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

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

我想使用 $1 作为我可以调用方法的变量,目前解释器返回一个 "NoMethodError: undefined method 'description' for "Door":String".

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

编辑:

例如:

door = Item.new( :name => "Door", :description => "a locked door" )
key  = Item.new( :name => "Key",  :description => "a key"         )

您需要提供代码设置的更多详细信息才能得到好的答案(或者让我找出哪个问题与 : 重复).$1 引用了哪些变量?以下是一些猜测:

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. 如果这实际上是同一实例上的一个方法,您可以通过以下方式调用此方法:

  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 

  • 如果这些是实例变量,则:

  • If these are instance variables, then:

    # Same as "@foo.description.downcase"
    instance_variable_get(:"@#{$1}").description.downcase
    

  • 如果这些是局部变量,你不能直接做,你应该改变你的代码以使用哈希:

  • 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