def bar(foo)
foo.nil? ? nil : foo.to_i
end
Any concise Ruby idiom for "foo.nil? ? nil : foo.to_i" ?
Or a little bit shorter (if you dont expect foo
to be false
)
def bar(foo)
foo.to_i if foo
end
def bar(foo)
foo.to_i unless foo.nil?
end
But you don't really gain anything, IMO, except eliminating the ? ?
. It's a character shorter, potentially more readable if you know Ruby. Don't know as it qualifies as "more concise" than the ternary.
(I say "potentially" because it might be considered non-obvious behavior in the nil
case.)
If you use ActiveSupport from rails you can write it using try
method
foo.try(:to_i)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With