Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby idiom for "foo.nil? ? nil : foo.to_i"?

Tags:

idioms

ruby

def bar(foo)
  foo.nil? ? nil : foo.to_i
end

Any concise Ruby idiom for "foo.nil? ? nil : foo.to_i" ?

like image 874
Chris Xue Avatar asked Apr 27 '12 10:04

Chris Xue


3 Answers

Or a little bit shorter (if you dont expect foo to be false)

def bar(foo)
  foo.to_i if foo
end
like image 167
Marcel Jackwerth Avatar answered Oct 04 '22 01:10

Marcel Jackwerth


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.)

like image 42
Dave Newton Avatar answered Oct 04 '22 03:10

Dave Newton


If you use ActiveSupport from rails you can write it using try method

foo.try(:to_i)
like image 24
caulfield Avatar answered Oct 04 '22 03:10

caulfield