Can I use .include? () In case case? Ruby

I started learning Ruby. I have a small project to create a game, and I tried to create a function that receives user input and processes 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 cannot determine that I typed the navigation. Is there a way to fix this, or if I'm completely out of my mind, can someone point me in the right direction?

I found a 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
+4
source share
2 answers

case if-elsif, - ( case):

while listen = $stdin.gets.chomp
  case
  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 an option"
  end

  print "> "
end
+8

if elsif

if listen.include?("navigate")
  # ...
elsif $player_items.include?(listen)
  # ...
end
0

Source: https://habr.com/ru/post/1662287/


All Articles