Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert a string to an existing class instance

Tags:

ruby

Given a class instance and a string, how do I convert the string to refer to the instance?

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)

I understand why I'm getting NoMethodError, but I haven't been able to work out how to convert the room string to refer to the existing instance of Room named lounge.

like image 797
Nick Avatar asked Jul 17 '26 17:07

Nick


1 Answers

perhaps trying to map rooms and get them by key?

class Room

  def enter
    puts "Welcome!"
  end
end

# Rooms are predefined
rooms = %w[lounge kitchen study].inject({}) { |f,c| f.update c => Room.new }

puts "Which room would you like to go to?"
print "> "
if room = rooms[gets.strip]
  room.enter
end

Or even simpler:

class Room

  def initialize room_type
    @room_type = room_type
  end

  def enter
    return puts 'Unsupported room type' unless %w[
      lounge kitchen study
    ].include?(@room_type)
    puts "Welcome to #{@room_type}!"
  end

end

puts "Which room would you like to go to?"
print "> "
room = Room.new(gets.strip)
room.enter

Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!