2

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?

Stefan
  • 109,145
  • 14
  • 143
  • 218
Joe
  • 132
  • 5
  • 1
    Not completely clear the part of the duplicated name, can you make an example. Try `a = b || a`. – iGian Mar 05 '20 at 15:17

3 Answers3

1

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"
yez
  • 2,368
  • 9
  • 15
1

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.

themetar
  • 11
  • 2
0

2 simple ways:

a = b.presence || a

Or

a = b || a
Juan Furattini
  • 776
  • 6
  • 9