Reputation: 1
Recently, I just wrote a simple game in Ruby. I needed the user to input a object's name which I created earlier.
When I give the variable name in the place of object's name, ruby thinks it is another string and outputs that
there is no such method(no method error)
How can I solve this?
class game
#somecode
def weapon_power
@power
end
end
object = game.new
x = gets #user inputs object
puts x.weapon_power
Upvotes: 0
Views: 435
Reputation: 595
I think you are asking how to instantiate your Game
object via it's name in a string.
x = gets
clazz = Object.const_get(x)
obj = clazz.new
If the class is already instantiated you'll have to do more work. Maybe something like this
gameInstance = Game.new
x = gets
case x
when 'Game'
puts gameInstance.weapon_power
else
puts 'Unknown input'
end
Possible duplicate of: How do I create a class instance from a string name in ruby?
Upvotes: 1
Reputation: 55898
You set the variable x
to the return value of the gets
method. This method always returns a String
object.
Now, in your code, you are trying to call the weapon_power
method on this String
object which naturally fails since Strings don't have such a method.
I'm not exactly sure what you want to achieve here in the first place though, but you can call the weapon_power
method on your object
like this:
object.weapon_power
As a final note, please be aware that in Ruby, class names (like your game
always have to start with a capital letter. It thus has to be spelled Game
instead. With your exact code, you would have received a SyntaxError
.
Upvotes: 1
Reputation: 7723
I'm not 100% I undestand what you want - looks like using the user input to identify a variable, correct?
If so, an easy way would be through a Hash:
object = game.new
objects = { "object" => object }
x = gets #user inputs object
puts objects[x].weapon_power # retrieve object named "object" and call the weapon-power on it
Benefit is that this would work with several objects in the Hash if needed.
Upvotes: 0