Comment écrire un interrupteur dans Ruby

Mots clés : rubyswitch-statementconditional-statementsruby

meilleur 5 Réponses Comment écrire un interrupteur dans Ruby

vote vote

90

case x when 1..5   "It's between 1 and 5" when 6   "It's 6" when "foo", "bar"   "It's either foo or bar" when String   "You passed a string" else   "You gave me #{x} -- I have no idea what to do with that." end 
vote vote

87

1 === 1           # => true Fixnum === Fixnum # => false 
obj = 'hello' case obj.class when String   print('It is a string') when Fixnum   print('It is a number') else   print('It is not a string or number') end 
Fixnum === 1 # => true 
obj = 'hello' case obj  # was case obj.class when String   print('It is a string') when Fixnum   print('It is a number') else   print('It is not a string or number') end 
vote vote

78

case n when 0   puts 'You typed zero' when 1, 9   puts 'n is a perfect square' when 2   puts 'n is a prime number'   puts 'n is an even number' when 3, 5, 7   puts 'n is a prime number' when 4, 6, 8   puts 'n is an even number' else   puts 'Only single-digit numbers are allowed' end 
score = 70  result = case score    when 0..40 then "Fail"    when 41..60 then "Pass"    when 61..70 then "Pass with Merit"    when 71..100 then "Pass with Distinction"    else "Invalid Score" end  puts result 
vote vote

67

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 
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 
vote vote

58

is_even = ->(x) { x % 2 == 0 }  case number when 0 then puts 'zero' when is_even then puts 'even' else puts 'odd' end 
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 
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 

Questions similaires