Elijah Murray
Elijah Murray

Reputation: 2172

Add if not nil?

How do I write a one-liner for the following?

x = y + (z if != nil)

I tried a few different things and also searched, but can't seem to find anything that's specific to this.

I tried:

x = y + z? z : 0

but that didn't work (syntax?) and even if it did, it feels sloppy.

Upvotes: 3

Views: 3440

Answers (2)

jstim
jstim

Reputation: 2432

Your second attempt was trying to nil-check z with the ternary operator. This might be a more visible nil-check:

x = y + (z || 0)

Just for fun, say you wanted to nil-check all of your values before adding:

[1,2,nil,4,7,nil,23].map(&:to_i).inject(&:+) # => 37

Update

Or as improved by @hirolau: (cleaner and faster)

[1,2,nil,4,7,nil,23].compact.inject(&:+) # => 37

Without the inject, here's my benchmark comparison (for n=1,000,000):

          user       system     total      real
compact:  0.520000   0.000000   0.520000   (0.516290)
to_i:     1.380000   0.000000   1.380000   (1.372772)

Upvotes: 5

Mike Manfrin
Mike Manfrin

Reputation: 2762

x = y + z.to_i

nil.to_i will return 0, so you'll be adding nothing.

Upvotes: 13

Related Questions