Assign the return of a method to a variable only if it is not nil

Asked

Viewed 18 times

0

I wonder if there is a more ruby-like way to assign the return of a method to a variable only if it is not nil.

An example code of how it would work in, say, an ugly way.

def meu_metodo(valor)
  valor if valor.even?
end

variavel = nil

[2, 3, 4, 5, 6].each do |valor|
  tmp = meu_metodo(valor)
  variavel = tmp unless tmp.nil?
  puts variavel
end

Color in a temporary variable to then perform the test, there is some way to perform this test already in the assignment?

Thank you.

1 answer

0

The most succinct way to write a type of non-nullity check of an object is by using variavel ||= objetivo, which is a contraction of the expression variavel = variavel || objetivo. Your code would look like this:

def meu_metodo(valor)
  valor if valor.even?
end

[2, 3, 4, 5, 6].each do |valor|
  tmp ||= meu_metodo(valor)
  puts(tmp) if tmp
end

It is important to note that this is only possible because tmp goes back to being nil at the beginning of each cycle of that each. If it is necessary to use a variable external to the block, for whatever reason, at some point it will have to be reset to nil, because if it is not done, it will only work for the first time when the result is not null or false.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.