【问题标题】:Ruby chaining methods with if-statement [duplicate]带有if语句的Ruby链接方法[重复]
【发布时间】:2014-11-27 11:22:16
【问题描述】:

我有以下几点:

def method(integer)  
  a = 3+integer
  a += 10 if "one"<"another"
end

我可以用链接方法以某种方式将它写在一行中吗?

类似a = 3+f += 10 if "one"&lt;"another"

【问题讨论】:

  • 你为什么要这样做?
  • 另外,这不是方法链。
  • 实际上我不应该将它包装在一个方法中,因为它是公式的一部分,但我觉得对于这个例子来说它会更自然。
  • 是的,现在我看到这个案例与链接无关
  • 不要创建多个问题来询问同一件事。 (stackoverflow.com/q/27166803/128421)。这两者之间的差异是微不足道的,第一个的答案应该足以回答这个。

标签: ruby methods chaining


【解决方案1】:

您可以使用三元运算符在一行中完成:

def method(integer)  
  a = integer + ("one"<"another" ? 13 : 3)
end

不过,请确保这样做不会损害代码的可读性。

【讨论】:

    【解决方案2】:

    由于and&amp;&amp; 都使用short-circuit evaluation,您可以使用:

    (a = 3+integer) and ("one"<"another") and  (a += 10) 
    

    上面写着'Using “and” and “or” in Ruby':

    and 用于将相关操作链接在一起,直到其中一个返回 nil 或 false

    关于 and 的另一种思考方式是反向 if 语句修饰符

    【讨论】:

    • 这符合我的任务目的。谢谢!
    【解决方案3】:
    a= 3+ integer + ("one"<"another" ? 10 : 0)
    

    3+ integer 会将3 添加到integer 值,如果条件为真,("one"&lt;"another" ? 10 : 0) 将返回 10,否则将返回 0。

    【讨论】:

    • 不要只输入代码。花时间解释为什么应该使用它。扔掉代码就像扔鱼一样。解释它是教他们如何钓鱼,这有助于他们下次避免问题。
    猜你喜欢
    • 2011-12-01
    • 1970-01-01
    • 2020-05-01
    • 2016-07-25
    • 1970-01-01
    • 1970-01-01
    • 2016-01-30
    • 2019-10-08
    • 1970-01-01
    相关资源
    最近更新 更多