Search
 
SCRIPT & CODE EXAMPLE
 

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
Comment

ruby case statement multiple conditions

case [condition_1, condition_2, condition_3]
when [true, true, true]  
  puts "case 1"
when [true, true, false]
  puts "case 2"
...
else  
  puts "Default"
end
Comment

ruby if statement multiple conditions

if (condition1 && condition2) && (condition3 || condition4) && condition5
	# do something
end
Comment

PREVIOUS NEXT
Code Example
Ruby :: rails remove model 
Ruby :: length validation rails 
Ruby :: ruby if statement one line 
Ruby :: rails form fields 
Ruby :: rails check if key exists 
Ruby :: ruby substring remove 
Ruby :: method delete rails not working 
Ruby :: ruby get the number of same element in array 
Ruby :: rails resources only 
Ruby :: ruby default method parameters 
Ruby :: uper case in ruby 
Ruby :: ruby group by 
Ruby :: rails convert image to base64 
Ruby :: ruby get current pid 
Ruby :: create_enum in rails 7 
Ruby :: how to use multiple ruby version in mac as per project 
Ruby :: rspec gem tutorial 
Ruby :: active admin with friendly_id 
Ruby :: run ruby script 
Ruby :: object service 
Ruby :: install ruby on rails ubuntu 18.04 
Ruby :: for loop with condition in ruby 
Ruby :: Rails checkbox checked/unchecked values 
Ruby :: multiple seeds in rails 6 
Ruby :: add key and value to first spot in hash ruby 
Ruby :: rails class reminders belongs_to creator 
Ruby :: ruby plus plus 
Ruby :: ruby on rails project 
R :: select columns without na in r 
R :: r stack data frames 
ADD CONTENT
Topic
Content
Source link
Name
1+7 =