Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I use .include?() in a case statement? Ruby

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
like image 804
MrSlippyFist Avatar asked Nov 29 '16 14:11

MrSlippyFist


People also ask

Can you use || IN case statement Ruby?

You can't use “||” in case names. But you can use multiple case names without using a break between them. The program will then jump to the respective case and then it will look for code to execute until it finds a “break”. As a result these cases will share the same code.

What does case do in Ruby?

The case statement is a multiway branch statement just like a switch statement in other languages. It provides an easy way to forward execution to different parts of code based on the value of the expression.


1 Answers

If you want to use a case instead of an if-elsif block, then you can write it like this (note the blank space after the 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
like image 112
spickermann Avatar answered Oct 27 '22 13:10

spickermann