0

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
0

3 Answers 3

1

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.

Sign up to request clarification or add additional context in comments.

Comments

1

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?

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.