1 min read

TIL: You Can Use Lambdas in Ruby Case Statements

Using lambdas inside Ruby case statements

Oh my, this one really got me, lambdas in case statements:

n = rand(1..10)

case n
when lambda { |x| x.even? }
  puts "#{n} is even"
else
  puts "#{n} is odd"
end

You can even use the proc-symbol shorthand

n = rand(1..10)

case n
when lambda(&:even?)
  puts "#{n} is even"
else
  puts "#{n} is odd"
end

You can  use stabby lambdas too:

n = rand(1..10)

case n
when -> (n) { n.even? }
  puts "#{n} is even"
else
  puts "#{n} is odd"
end