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

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

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

+5
source share
8 answers

Or a little shorter (unless you expect it to foobe false)

def bar(foo)
  foo.to_i if foo
end
+6
source
def bar(foo)
  foo.to_i unless foo.nil?
end

But you get nothing, IMO, except elimination ? ?. This character is shorter, potentially more readable, if you know Ruby. I don’t know how he qualifies as “shorter” than ternary.

(I say “potentially” because in the case nilthis may be considered non-obvious behavior).

+4
source
foo and foo.to_i

.

  • foo - nil, foo.to_i .
  • foo nil, foo.to_i .
+4

ActiveSupport , try

foo.try(:to_i)
+3

, ..

foo = (foo.nil? ? nil : foo.to_i)

foo &&= foo.to_i
+2

andand gem

http://andand.rubyforge.org/

:

foo.andand.to_i

nil, foo nil, to_i else.

+1

foo && foo.to_i

ruby ​​2.3.0 , , " " . , , :

foo&.to_i

.

PS: .

.

+1

Ruby.

We can write code in four different ways:

Usage if:

def bar(foo)
  foo.to_i if foo
end

Usage unless:

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

Using the method trywhen using Rails:

def bar(foo)
  foo.try(:to_i)
end

Using the operator &.(Ruby's secure navigation operator) when using Ruby 2.3.x:

def bar(foo)
  foo&.to_i
end

For a more idiomatic way to write Ruby code , I read a great post about it.

0
source

All Articles