rib3ye
rib3ye

Reputation: 2923

Can I reuse conditions in nested if statements?

Is it possible to reuse a condition from a parent if statement?

Example:

if a == b || a == c
    if a == b
        #do thing
    elsif a == c
        #do the other thing
    end
    #in addition to this thing
end

Can the initial a == b or a == c be referenced in the nested statements without manually retyping them?

Upvotes: 1

Views: 237

Answers (3)

Cary Swoveland
Cary Swoveland

Reputation: 110675

I suggest the following.

case a
when b
  ...
  common_code
when c
  ...
  common_code
end

def common_code
  ...
end

Upvotes: 2

anquegi
anquegi

Reputation: 11522

As pointed in the comment in ruby, the process of storing a variable inside returns the value of the variable so you can do this:

a = 3
b = 4
c = 3

if cond1 = a == b || cond2 =  a == c then
    if cond1 then
        puts "a==b"
    elsif cond2
        puts "a==c"
    end
    puts "do this"

end

the result

irb(main):082:0> a==b
do this
=> true
i

Upvotes: 2

sawa
sawa

Reputation: 168081

Perhaps you can use a flag.

if a == b
  flag = true
  # do thing
elsif a == c
  flag = true
  # do the other thing
else
  flag = false
end
if flag
  # in addition to this thing
end

or

flag =
case a
when b
  # do thing
  true
when c
  # do the other thing
  true
else
  false
end
if flag
  # in addition to this thing
end

Upvotes: 0

Related Questions