4 ms·
even = ->(x) { x % 2 == 0 } even === 4 # true even === 5 # false That's cool. No need for a is_even or is_odd gem. I really do like that ability to
by hk1337 4y ago
even = ->(x) { x % 2 == 0 }
even === 4 # true
even === 5 # false
That's cool. No need for a is_even or is_odd gem.
I really do like that ability to do a case statement though. I cannot think of a situation where I need it now but I could definitely see it being handy instead of having to do if..else if
- chao- 4y agoAlternatively you can call Integer#even? or Integer#odd? directly: 4.even? # true 5.even? # false Or if you really want to use ===, it is possible with the slightly sillier (imho) use of Symbol#to_proc: case some_num when :zero?.to_proc then "zero" when :even?.to_proc then "even" when :odd?.to_proc then "odd" end I say sillier, because even though it is very explicit, the use of #to_proc, by name, feels just a tiny bit less awesome than its usual use via the & operator, e.g. array_of_nums.map(&:odd?). It would be really cool to be able to write: case some_num when &:zero? then "zero" when &:even? then "even" when &:odd? then "odd" end However I say this with no grasp of just how complex that could be to implement, or other implications for the language's grammar.