Reputation: 23
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
Reputation: 29950
Why not:
a = b unless b.nil?
or:
b.nil? and a = b
They aren't they readable oneliners?
Upvotes: 0
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
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