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 :: ruby reduce hash 
Ruby :: ruby loop using integer 
Ruby :: ruby if else 
Ruby :: rails sendgrid setup 
Ruby :: stripe test keys 
Ruby :: ruby convert value to boolean 
Ruby :: ide for ruby 
Ruby :: ruby on rails sum nil 
Ruby :: map each with index 
Ruby :: how to unloack user devise rails 
Ruby :: ruby rspec change matcher 
Ruby :: Hash.new constructor 
Ruby :: render to string rails 
Ruby :: stringio original_filename 
Ruby :: how to know current schema database in rails 
Ruby :: csv file current row number ruby 
Ruby :: how to comment out embedded ruby 
Ruby :: ruby plus plus 
Ruby :: how to use custom switch in rails 
R :: r convert accented characters 
R :: r remove leading and trailing whitespace 
R :: R regress one variable on all the other variables 
R :: r dataframe column factor 
R :: comment in r 
R :: if not NA in r 
R :: r environment variables 
R :: R squared regression in r with ggplot 
R :: R language get all columns in a dataset 
R :: how to source all fies from a directory in r 
R :: apply function to all vector elements r 
ADD CONTENT
Topic
Content
Source link
Name
4+7 =