Me
Blog about Ruby, Rails, and more!

Using lambdas with case statements

2017-08-13

Let's be honest, no one likes to see a long chain of if/elsif mucking up a codebase. A nice alternative to long if/elsif chains is to use a case statement. This is easy enough for comparing strings or symbols, but what do you do if you need to actually call methods on your case variable?

For example, imagine you have a rails model with several predicate methods. Lets call our example model Book. Lets assume our Book models has several predicate methods used to determine a books status; fulfilled?, processing?, completed?, and cancelled?.

You can use these predicate methods within a case statement, like so:

new_order = Order.new
case new_order
when -> (order) { order.fulfilled? }
  'your order is filfilled!'
when -> (order) { order.processing? }
  'your order is processing!'
when -> (order) { order.completed? }
  'your order is completed!'
when -> (order) { order.cancelled? }
  'your order is cancelled!'
else
  raise 'UndefinedStatusError'
end

You could also use this to run some code only if a hash has certain keys: ```ruby case myhash when -> (hash) { hash[:keya] } 'hash has keya' wher -> (hash) { hash[:keyb] } 'hash has key_b' end

IMO this definitely looks cleaner than a long chaing of if/elsif statements.