How to make a switch in Ruby?

Asked

Viewed 4,080 times

1

How can I make a switch in Ruby?

  • 3

    Could present some research effort.

  • 2

    Several examples: http://stackoverflow.com/questions/948135/how-can-i-write-a-switch-statement-in-ruby

  • 1

    I don’t know why people are giving down votes to the @Mayra question. It is a doubt that many beginners have, and can be useful to many people, because for those who come from other languages is very different.

1 answer

8


In this case Ruby uses the structure case...when

case objeto
when 1
  puts "Seu número é 1"
when 2..10
  puts "Seu número está entre 2 e 10"
when 11,13,17,19
  puts "é um número primo entre 10 e 20"
when String
  puts "é uma String"
else
  puts "Qualquer outra coisa."
end

You can create this structure without parenting as well

case
when objeto < 10
  puts "Menor que 10"
when objeto == 10
  puts "Igual a 10"
when (10..20) === b
  puts "Alguma coisa entre 10 e 20"
end

And also Ruby interprets all kinds of instruction as the case when/ if else anyway... That is to say:

    objeto = 1
    variable_to_return = case objeto
                           when 1
                             10
                           else 
                             'UAHEUHAUEHUAEHUAE sou uma String!'
                         end
   puts variable_to_return  # => 10
  • 1

    Thank you Luiz Carvalho

Browser other questions tagged

You are not signed in. Login or sign up in order to post.