【发布时间】:2017-05-29 08:23:22
【问题描述】:
我尝试使用速记来获得基于子字符串存在的响应,而不是预期的字符串响应,它评估为“假”。在我的第二个更简单的例子中,expect 字符串被打印出来了。
#fails
puts "test".include? "s" ? "yep" : "nope"
#success
puts 1>2 ? "1 is greater than 2" : "1 is not greater than 2"
【问题讨论】:
我尝试使用速记来获得基于子字符串存在的响应,而不是预期的字符串响应,它评估为“假”。在我的第二个更简单的例子中,expect 字符串被打印出来了。
#fails
puts "test".include? "s" ? "yep" : "nope"
#success
puts 1>2 ? "1 is greater than 2" : "1 is not greater than 2"
【问题讨论】:
这是precedence 的问题。
你需要:
puts "test".include?("s") ? "yep" : "nope"
#=> yep
不带括号的方法调用在优先表中位于defined? 和or 之间,因此它低于三元运算符。这意味着
puts "test".include? "s" ? "yep" : "nope"
被解析为
puts "test".include?("s" ? "yep" : "nope")
这是
puts "test".include?("yep")
这是
false
"s" ? "yep" : "nope"
显示警告:
warning: string literal in condition
因为三元运算符需要一个布尔值,而字符串总是真实的。
这行得通的原因
puts 1>2 ? "1 is greater than 2" : "1 is not greater than 2"
是三元运算符的优先级高于puts:
puts ( 1>2 ? "1 is greater than 2" : "1 is not greater than 2" )
它被评估为:
puts ( "1 is not greater than 2" )
当您遇到优先级问题时,使用不带括号的puts 可能只会使问题变得更糟。您可以启动 IRB 并直接查看结果。
这是一个例子:
# in a script :
puts [1,2,3].map do |i|
i * 2
end
#=> #<Enumerator:0x0000000214d708>
使用 IRB:
[1,2,3].map do |i|
i * 2
end
# => [2, 4, 6]
【讨论】:
在没有一点帮助的情况下,ruby 似乎无法按照您的预期解析它。它认为你在做
puts "test".include?("s" ? "yep" : "nope")
您需要在参数周围使用(可选)括号
puts "test".include?("s") ? "yep" : "nope"
或强制将测试表达式解释为一个整体:
puts ("test".include?"s") ? "yep" : "nope"
【讨论】:
?。