【问题标题】:Why does using the shorthand "if" syntax does not evaluate when searching for a sub-string using "include?"为什么在使用“include”搜索子字符串时使用速记“if”语法不计算?
【发布时间】: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"

【问题讨论】:

    标签: ruby conditional-operator


    【解决方案1】:

    这是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
    

    因为三元运算符需要一个布尔值,而字符串总是真实的。

    1 > 2

    这行得通的原因

    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]
    

    【讨论】:

    • 这个答案正在成为史诗。喜欢它。
    • 绑定强度是这里的关键。优先级是一个更笼统的术语,意思相同。
    • @tadman :有趣,谢谢。我刚刚搜索了“Binding strength Ruby”,大部分都在 SO 上找到了你的答案。你有什么参考吗?
    • @EricDuminil 这里关于优先级的第一个链接确定了正在发生的事情。结合力是概念化正在发生的事情的另一种方式。
    • 也许我发明了这个术语并说服自己这是一件事,或者它可能是我应用于编程的化学术语。感谢您指出这一点。
    【解决方案2】:

    在没有一点帮助的情况下,ruby 似乎无法按照您的预期解析它。它认为你在做

    puts "test".include?("s" ? "yep" : "nope")
    

    您需要在参数周围使用(可选)括号

    puts "test".include?("s") ? "yep" : "nope"
    

    或强制将测试表达式解释为一个整体:

    puts ("test".include?"s") ? "yep" : "nope"
    

    【讨论】:

    • 为什么会被否决?我不明白。反对者:请发表评论。
    • 不知道为什么,但缺少大写字母可能会让人们陷入低迷的投票愤怒中。
    • 另外,您的第一个 sn-p 中缺少 ?
    猜你喜欢
    • 2011-08-15
    • 1970-01-01
    • 2010-12-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多