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!
Written by Hannes Georg
Related protips
Have a fresh tip? Share with Coderwall community!
Post
Post a tip
Best
#Ruby
Authors
Sponsored by #native_company# — Learn More
#native_title#
#native_desc#