Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
315 views
in Technique[技术] by (71.8m points)

ruby - Why doesn't `array.include` [sic] show the correct output

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...