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 :: helper path outside view 
Ruby :: Rails public folder items not available in production 
Ruby :: create table index unique rails 
Ruby :: ruby array split into groups 
Ruby :: Blocked host: c25f383bd08f.ngrok.io 
Ruby :: ffi gem error mac 
Ruby :: ruby loop over files in a folder 
Ruby :: including libraries in ruby 
Ruby :: rails resources 
Ruby :: rails change database connection 
Ruby :: rails log levels 
Ruby :: ruby coding challenges 
Ruby :: for loop with condition in ruby 
Ruby :: ruby puts inspect 
Ruby :: sidekiq configuration file 
Ruby :: ruby block_given? method 
Ruby :: rails add index from console 
Ruby :: rails convert euro to dollar 
Ruby :: ruby hash except nested 
Ruby :: rails print number with space 
Ruby :: allow raise inside rescue rspec 
R :: vertical line in ggplot2 
R :: r remove na from dataset 
R :: read csv file in r 
R :: sort dataframe r 
R :: import excel into r 
R :: R get specific character from string 
R :: r - remove NA from a coulm 
R :: remove column from matrix r 
R :: replace character with na r 
ADD CONTENT
Topic
Content
Source link
Name
4+7 =