Alex Rivera | Logout

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

Asked 2012-11-03T11:28:56.493
9

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?

Edit
Report

1 Answer

6

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
answered 2012-11-03T12:03:46.043

Your Answer