-2

I have:

num = ["jack","sparrow","terminator","leonidus"]
name = "jack"

The solution is:

if num.include? name
  puts " Jack is here"
else
  puts " Invite jack"
end
# => "Jack is here"

My old script is:

val = num.include? name
if val == "true"
  puts " Jack is here"
else
  puts " Invite jack"
end
# => "Invite jack"

Why is my old script not working? What is wrong with it?

sawa
  • 165,429
  • 45
  • 277
  • 381

2 Answers2

1
true == "true"
# => false

true is not equal to "true" even though "true" is a truthy value, that is, casted to boolean it will result true (nil is falsy, surprisingly 0 is truthy). To cast something to its boolean value, you can use this syntax: !!variable. You don't need to do that inside the if condition because it's already done internally.

sawa
  • 165,429
  • 45
  • 277
  • 381
Damiano Stoffie
  • 897
  • 5
  • 8
0

The include method returns a boolean value. So your solution eliminates one of the steps, which is great. The old script didn't work because you were trying to compare a boolean value to a string. You could take away your quotes on true and you would have come up with a working solution: if val == true. Hope this helps.

sclem72
  • 466
  • 6
  • 16
  • Yes, and since it's a check for boolean value, using just `val` would be enough here :) – Lahiru Jayaratne Nov 23 '15 at 17:43
  • @sawa It is a method that is used on an array that asks the array if it includes the argument that is passed in. For example: `[1, 2, 3, 4, 5].include?(2) # true` `[1, 2, 3, 4, 5].include?(10) # false` – sclem72 Nov 23 '15 at 20:42
  • There is no such method. Also, your explanation and the example in the comment do not match. – sawa Nov 23 '15 at 22:35
  • Your explanation is "Easy" and to the point, thanks for help. – Tushar Khan Nov 24 '15 at 06:51