Use a string to access a local variable by name

I am 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, the interpreter currently returns "NoMethodError: undefined method 'description' for "Door":String" .

Edit

For instance:

 door = Item.new( :name => "Door", :description => "a locked door" ) key = Item.new( :name => "Key", :description => "a key" ) 
+6
source share
2 answers

You need to provide more detailed information on setting up the code in order to get a good answer (or for me to find out which question is a duplicate :). What variables are referenced by $1 ? Here are a few hunches:

  • If this is really a method in one instance, you can call this method with:

     # 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 cannot do this directly, and you must change your code to use the 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 
+9
source

I assume that you have matched a line like read door with / ^ read (. +) $ /. So, $ 1 = "Door", and he raised the above error. If you want to delete this line just use:

$ 1.downcase

0
source

Source: https://habr.com/ru/post/887511/


All Articles