给定一个类实例和一个字符串,如何将字符串转换为引用该实例?
class Room
def enter
puts "Welcome!"
end
end
# Rooms are predefined
lounge = Room.new
kitchen = Room.new
study = Room.new
puts "Which room would you like to go to?"
print "> "
room = gets.strip
# User types "lounge"
room.enter # => undefined method `enter' for "lounge":String (NoMethodError)
我理解为什么我会收到 NoMethodError,但我无法弄清楚如何将room
字符串转换为引用 Room 的现有实例 named lounge
。