user1118767
user1118767

Reputation: 23

In ruby, is there any operator similar to ||= for the assignment: a = b if !b.nil?

Just as the title asks, is there an operator, or some snazzy one liner to do the above?

To clarify, if this is the first time a is being referenced, and b is nil, a shouldn't persist past the evaluation of b being nil.

Upvotes: 2

Views: 169

Answers (3)

Pedro Rolo
Pedro Rolo

Reputation: 29950

Why not:

a = b unless b.nil?

or:

b.nil? and a = b

They aren't they readable oneliners?

Upvotes: 0

Frederick Cheung
Frederick Cheung

Reputation: 84132

In ruby local variables can spring into existence without a line assigning to them actually being executed:

a #=> NameError ...
if false
  a = 1
end
a #=> nil

Your snippet is equivalent to

if !b.nil?
  a = b
end

If b is nil, then the assignment is not executed, and from the previous example this will set the value of a to nil. If b is not nil then a is set to the value of b. So this (somewhat surprisingly) is actually the same as

a = b

But only if a doesn't exist yet, and thus a very error prone way of doing things. Don't do this!

Upvotes: 0

dj2
dj2

Reputation: 9618

There is no operator that I know of. Your response is already one line ... If you really wanted you can change the if ! to unless.

Upvotes: 1

Related Questions