lulalala
lulalala

Reputation: 17981

Why can't a variable initialized in an `if` condition be used in the if's block?

So it is common to initialize a variable in an if condition, and then use that variable inside the if's block.

if a = foo()
   puts a
end

However when I initialize a variable and use it in the same if's block, that var will not be considered initialized at that time. For example:

def good?(item)
  puts "item is #{item.inspect}"
  true
end

if b = 52 && good?(b)
  puts "b is #{b.inspect}"
end

Run the above and the result would be

item is nil
b is true

Why is this the case? What kind of keyword is related to this Ruby behavior that I search for and study about it?

Upvotes: 1

Views: 184

Answers (2)

Oka
Oka

Reputation: 26355

You're assigning to b the result of 52 && good?(b). b is still nil when it is passed to good?.

Parenthesis are the key.

def good?(item)
  puts "item is #{item.inspect}"
  true
end

if (b = 52) && good?(b)
  puts "b is #{b.inspect}"
end

Result:

item is 52
b is 52

Upvotes: 8

Yu Hao
Yu Hao

Reputation: 122393

The precedence of && is higher than =, so

if b = 52 && good?(b)

is equivalent to:

if b = (52 && good?(b))

Reference: Operator Precedence.

Upvotes: 9

Related Questions