Last Updated: April 04, 2020
·
2.522K
· hannesg

Use lambdas with case/when

Few people know that Proc#=== is actually an alias for Proc#call. This allows a Proc to be used as predicate for when and therefore allows to mix classtyping and ducktyping:

case( variable )
when Hash then "Real Hash"
when proc{|x| x.respond_to? :[] } then "Responds to :[]"
end

This becomes even cooler with the new rocket syntax:

case( variable )
when Hash then "Real Hash"
when ->x{ x.respond_to? :[] } then "Responds to :[]"
end

Nice!