I have started to learn Ruby. I have a small project to build a game and tried to create a function that receives user input and handles it accordingly.
def Game.listener
print "> "
while listen = $stdin.gets.chomp.downcase
case listen
when (listen.include?("navigate"))
puts "Navigate to #{listen}"
break
when ($player_items.include?(listen))
Items.use(listen)
break
end
puts "Not a option"
print "> "
end
end
However, the case statement is unable to detect I have typed navigate. Is there a way to fix this or if I'm totally off can someone point me in the right direction?
I have found this way to solve my problem, is it a safe and reliable way?
while listen = $stdin.gets.chomp
case listen.include?(listen)
when listen.include?("navigate")
puts "Navigate to #{listen}"
when listen.include?("test")
puts "test"
when $player_items.include?(listen)
puts "Using the #{$player_items[listen]}"
break
else
puts "Not a option"
end
print "> "
end
[]
-notation,scan
ormatch
. – Koine(listen.include?("navigate"))
equalstrue
orfalse
, so the line following is executed iflisten
equals that logical value. That's not what you want. You need to changecase listen
tocase
. – Joelynnr = /\bhello\b/; listen[r]; listen.scan(r); listen.match(r)
. See square-bracket notation, String#scan and String#match for more info. – Koinelisten
is aString
,listen.include?('navigate')
is a boolean. A boolean will never be equal to nor will it match aString
, therefore that branch can never execute … and the same for all the other branches. – Triclinic