0

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
4thSpace
  • 43,672
  • 97
  • 296
  • 475
  • 1
    Not an exact duplicate, but essentially the answer is that things that aren't `false` or `nil` are true. – 4castle Aug 15 '16 at 04:22
  • 2
    Your `if` conditional first checks if `num_1`, so basically if it has a truthy value set to it (i.e. a value exists for the variable, and is not null or false). Then (`&&`) the conditional checks `num_2 == "1"`, which in this case is `true`.. – philip yoo Aug 15 '16 at 04:40

1 Answers1

1

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.

Robert Columbia
  • 6,313
  • 15
  • 32
  • 40
  • "`num_1`, `num_2`, and `"1"` all evaluate to `true` when used with a boolean operator" is incorrect. They are truthy, but they are never evaluated to `true`. For example, `"1" && "2"` evaluates to `"2"`, not `true`. – Amadan Aug 15 '16 at 05:02
  • @Amadan point taken, thanks. – Robert Columbia Aug 15 '16 at 05:22