0

I want to take any truthy value from two expressions, for example 2, or take nothing. It can be done as:

if exp1
  a = exp1
elsif exp2
  a = exp2
end

I tried to make it short, and have the following:

a = 1 if exp1|| 2 if exp2

However ruby returns 1 in this case. What is the correct syntax in ruby to do this?

sawa
  • 165,429
  • 45
  • 277
  • 381
Joel Blum
  • 7,750
  • 10
  • 41
  • 60

4 Answers4

8

This should work:

a = exp1 || exp2 || a
Stefan
  • 109,145
  • 14
  • 143
  • 218
1
a = exp1 ? exp1 : exp2 ? exp2 : a

Equivalent to:

if exp1,
    a is set to exp1
else if exp2,
    a is set to exp2
else
    a is set to a, which is virtually equivalent to doing nothing
konsolebox
  • 72,135
  • 12
  • 99
  • 105
0

The correct syntax:

a = (1 if false) || (2 if true)
hypersolid
  • 56
  • 4
  • I accepted it by mistake... it's not what I needed . I want my variable to keep it's original value if both conditions are falsy but that doesn't happen here.the only way that I can see is the long way I wrote in my question. – Joel Blum Jul 30 '14 at 14:05
0
if exp1
  a = exp1
elsif exp2
  a = exp2
end

Can be shortened to

a = if exp1
  exp1
elsif exp2
  exp2
end

Or, if you prefer one-liners:

a = if exp1 then exp1 elsif exp2 then exp2 end

Any attempt to shorten it even further will change the semantics. For example:

a = exp1 || exp2 || nil

will evaluate exp1 exactly once and exp2 at most once, whereas the original snippet will evaluate exp1 once or twice and exp2 either twice or never.

(To be fair: my example will also change the meaning IFF a appears in exp1. In the OP's original code, an occurrence of a in exp1 will be interpreted as a method call, in my example as a local variable dereference which will evaluate to nil.)

Jörg W Mittag
  • 363,080
  • 75
  • 446
  • 653