Search
 
SCRIPT & CODE EXAMPLE
 
CODE EXAMPLE FOR RUBY

ruby case when multiple conditions

# Five techniques (param, no param, regex, when/then, *array)

# With paramater
value=88
case value
when 1
  puts "Single value"
when 2, 3, 4
  puts "One of comma-separated values"
when 5..7
  puts "One of 5, 6, 7"
when 7...10
  puts "One of 8, 9, but not 10"
when "foo", "bar"
  puts "It's either foo or bar"
when String
  puts "You passed a string"
when ->(x) { x % 2 == 0 }
  puts "Even number (found this using lambda)"
else
  puts "Something else"
end

# Without paramater
value=4
case
when value < 3
  puts "Less than 3"
when value == 3
  puts "Equal to 3"
when (1..10) === value
  puts "Something in closed range of [1..10]"
end

# Using regular expressions
input = "hello 123"
case
when input.match(/d/)
  puts 'String has numbers'
when input.match(/[a-zA-Z]/)
  puts 'String has letters'
else
  puts 'String has no numbers or letters'
end

# When/Then single line calls
score = 70
case score
when 0..40 then puts "Fail"
when 41..60 then puts "Pass"
when 61..70 then puts "Pass with Merit"
when 71..100 then puts "Pass with Distinction"
else "Invalid Score"
end

# Find element in array
element = 3
array = [1, 2, 3, 4, 5]
case element
when *array 
  puts 'found in array'
else
  puts 'not found in array'
end
Source by stackoverflow.com #
 
PREVIOUS NEXT
Tagged: #ruby #case #multiple #conditions
ADD COMMENT
Topic
Name
1+1 =