Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
332 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 Reply

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...