How to write a switch statement in Ruby

2018-12-31 23:16发布

How do I write a switch statement in Ruby?

21条回答
谁念西风独自凉
2楼-- · 2018-12-31 23:38

In Ruby 2.0, you can also use lambdas in case statements, as follows:

is_even = ->(x) { x % 2 == 0 }

case number
when 0 then puts 'zero'
when is_even then puts 'even'
else puts 'odd'
end

You can also create your own comparators easily using a Struct with a custom ===

Moddable = Struct.new(:n) do
  def ===(numeric)
    numeric % n == 0
  end
end

mod4 = Moddable.new(4)
mod3 = Moddable.new(3)

case number
when mod4 then puts 'multiple of 4'
when mod3 then puts 'multiple of 3'
end

(Example taken from "Can procs be used with case statements in Ruby 2.0?".)

Or, with a complete class:

class Vehicle
  def ===(another_vehicle)
    self.number_of_wheels == another_vehicle.number_of_wheels
  end
end

four_wheeler = Vehicle.new 4
two_wheeler = Vehicle.new 2

case vehicle
when two_wheeler
  puts 'two wheeler'
when four_wheeler
  puts 'four wheeler'
end

(Example taken from "How A Ruby Case Statement Works And What You Can Do With It".)

查看更多
查无此人
3楼-- · 2018-12-31 23:38

If you are eager to know how to use an OR condition in a Ruby switch case:

So, in a case statement, a , is the equivalent of || in an if statement.

case car
   when 'Maruti', 'Hyundai'
      # Code here
end

Many other things you can do with a Ruby case statement

查看更多
梦寄多情
4楼-- · 2018-12-31 23:40

You can write case expressions in two different ways in ruby.

  1. Similar to a series of "if" statements
  2. Specify a target next to the case and each "when" clause is compared to the target.

1st way

age = 20
case 
when age >= 21
puts "display something"
when 1 == 0
puts "omg"
else
puts "default condition"
end

2nd way

 case params[:unknown]
 when /Something/ then 'Nothing'
 when /Something else/ then 'I dont know'
 end
查看更多
呛了眼睛熬了心
5楼-- · 2018-12-31 23:42

case...when

To add more examples to Chuck's answer:

With parameter:

case a
when 1
  puts "Single value"
when 2, 3
  puts "One of comma-separated values"
when 4..6
  puts "One of 4, 5, 6"
when 7...9
  puts "One of 7, 8, but not 9"
else
  puts "Any other thing"
end

Without parameter:

case
when b < 3
  puts "Little than 3"
when b == 3
  puts "Equal to 3"
when (1..10) === b
  puts "Something in closed range of [1..10]"
end

Please, be aware of the issue that kikito warns.

查看更多
大哥的爱人
6楼-- · 2018-12-31 23:42

As stated in many of the above answers, the === operator is used under the hood on case/when statements.

Here is a few extra information about that operator.

Case equality operator: ===

Many of Ruby's built-in classes, such as String, Range, and Regexp, provide their own implementations of the === operator, also known as case-equality, triple equals or threequals. Because it's implemented differently in each class, it will behave differently depending on the type of object it was called on. Generally, it returns true if the object on the right "belongs to" or "is a member of" the object on the left. For instance, it can be used to test if an object is an instance of a class (or one of its subclasses).

String === "zen"  # Output: => true
Range === (1..2)   # Output: => true
Array === [1,2,3]   # Output: => true
Integer === 2   # Output: => true

The same result can be achieved with other methods which are probably best suited for the job, such as is_a? and instance_of?.

Range Implementation of ===

When the === operator is called on a range object, it returns true if the value on the right falls within the range on the left.

(1..4) === 3  # Output: => true
(1..4) === 2.345 # Output: => true
(1..4) === 6  # Output: => false

("a".."d") === "c" # Output: => true
("a".."d") === "e" # Output: => false

Remember that the === operator invokes the === method of the left-hand object. So (1..4) === 3 is equivalent to (1..4).=== 3. In other words, the class of the left-hand operand will define which implementation of the === method will be called, so the operand positions are not interchangeable.

Regexp Implementation of ===

Returns true if the string on the right matches the regular expression on the left. /zen/ === "practice zazen today" # Output: => true # is similar to "practice zazen today"=~ /zen/

The only relevant difference between the two examples above is that, when there is a match, === returns true and =~ returns an integer, which is a truthy value in Ruby. We will get back to this soon.

查看更多
零度萤火
7楼-- · 2018-12-31 23:43
puts "Recommend me a language to learn?"
input = gets.chomp.downcase.to_s

case input
when 'ruby'
    puts "Learn Ruby"
when 'python'
    puts "Learn Python"
when 'java'
    puts "Learn Java"
when 'php'
    puts "Learn PHP"
else
    "Go to Sleep!"
end
查看更多
登录 后发表回答