4thSpace 4thSpace - 3 months ago 10
Ruby Question

Why is this condition true?

Why is the following condition true? I was thinking the equality would apply to both variables but it doesn't. Even if they are surrounded in parentheses.

What is num_1 evaluating to that it is true?

num_1 = "2"
num_2 = "1"

if num_1 && num_2 == "1"
puts "condition met"
end


I'm aware the following is what I intended to check:

if num_1 == "1" && num_2 == "1"
puts "condition met"
end

Answer

num_1, num_2, and "1" all evaluate to true when used with a boolean operator. In Ruby, all strings are "truthy". As Philip Yoo mentioned, this results in a true expression num_2 == "1", which evaluates to true, being anded with true, and that is true.