Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby: Assign output of a function only if it does not return nil

When programming in Ruby I quite often have assignments like the following

test = some_function if some_function

With that assignments I want to assign the output of a function, but if it returns nil I want to keep the content of the variable. I know there are conditional assignments, but neither ||= nor &&= can be used here. The shortest way I found to describe the statement above is

test = (some_function or test)

Is there a better / shorter way to do this?

like image 802
Florian Feldhaus Avatar asked Nov 03 '12 11:11

Florian Feldhaus


2 Answers

I don't think there's anything better than the last snippet you showed but note that or is used for flow control, use || instead:

test = some_function || test

It's usually better to assign new values to new names, the resulting code is easier to understand and debug since variables/symbols have the same value throughout the scope:

some_different_and_descriptive_name_here = some_function || test
like image 173
tokland Avatar answered Nov 08 '22 09:11

tokland


I'd just add parentheses

(a = b) unless b.nil?

(a = b) if b

being inferior because if b is false then a remains as before

Keep in mind that this evaluates b twice, so if b is a function with side-effects (such as changing variables outside of its scope or printing) it will do that twice; to avoid this you must use

temp = b; (a = temp) unless temp.nil?

(which can, of course, be split into)

temp = b

(a = temp) unless temp.nil?

like image 34
Andrew Wonnacott Avatar answered Nov 08 '22 10:11

Andrew Wonnacott