Xenon Xenon - 1 year ago 77
Ruby Question

How to write a conditional lambda in Ruby?

I'd like to write a conditional lambda in Ruby. The Python equivalent of what I'd like to write is:

even = (lambda x: x if x % 2 == 0 else 0)

My attempt to write this in Ruby looks like:

even = -> (x) {x if x % 2 == 0 else 0}

Unfortunately, that does not work. Is there any way to fix this?

Answer Source

You have several options here to express this. The long-form is this:

if (x % 2 == 0)

Note that a trailing if or unless cannot have a secondary condition like else. You need to use the full form.

If you want a short version, you use the ternary operator:

(x % 2 == 0) ? x : 0

What you could also do is this:

(x % 2 == 0) and x or 0

As others have observed there's a method called even? which does the modulo for you, so that can collapse this further:

x.even? ? x : 0
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download