Simplify Assignment in Ruby on Rails

Viewed 107

I just want to assign the value of variable B to variable A only if B is not nil. And I want to simplify the code as possible. So I found the one.

A = B if B

But variable name is long such as data[:Symbol1][:Symbol2]... , anyhow same variable name is duplicated.

Can anybody help me with simplifying this code?

3 Answers

You might try the presence method.

Your code would look like

A = B.presence

Example of it in action:

[1] pry(main)> b = nil
=> nil
[2] pry(main)> a = b.presence
=> nil
[3] pry(main)> a
=> nil
[4] pry(main)> b = 'foo'
=> "foo"
[5] pry(main)> a = b.presence
=> "foo"
[6] pry(main)> a
=> "foo"

I'd say you need A = B || A.

The || operator evaluates and returns the first non-false operand. If B is "truthy", it will return B (and assign it to A). If B is false, A will just be assigned itself.

2 simple ways:

a = b.presence || a

Or

a = b || a
Related