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" )
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:
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With