【问题标题】:Correct way of writing parentheses in Ruby methods?在 Ruby 方法中编写括号的正确方法?
【发布时间】:2013-03-20 22:54:40
【问题描述】:

在 Ruby 方法中写括号的“可接受”或“正确”方式是什么?

喜欢:

puts doc.instance_of?( self.class.superclass.class )

或:

puts doc.instance_of? ( self.class.superclass.class )

或:

puts doc.instance_of? (self.class.superclass.class)

或:

puts doc.instance_of?(self.class.superclass.class)

【问题讨论】:

    标签: ruby coding-style


    【解决方案1】:

    2 和 3 是错误的(请参阅@muistooshort 的评论)。

    在 1 和 4 之间,只需选择一个风格指南并坚持下去。一致性是最重要的。我对推荐 1 的这个很满意,个人觉得它看起来更干净:

    https://github.com/styleguide/ruby

    这是一个使用可选第二个参数的方法打破 2 的示例:

    def f(x, y=1) x + y end
    
    f(1,2) # 3
    
    f(1) # 2
    
    f (1, 2) # syntax error
    
    f (1), 2 # 3!
    

    【讨论】:

    • 嗯,我想说 1 也不是惯用的,您链接的指南也说:“(”之后没有空格。它看起来很糟糕。
    • 实际上,f (x,y) 甚至无效;如果方法后有空格,则括号用于分组。如果您要在方法调用中使用括号,它们必须跟在方法名称之后,它们之间不能有任何空格,否则括号的含义完全不同。所以1和4没问题,2和3一般都是废话。
    【解决方案2】:

    您甚至可以在 Ruby 中省略括号,就像在所有示例中为 puts 省略括号一样。这是“常用方式”,除非您有复杂的表达式或优先级问题。

    puts doc.instance_of? self.class.superclass.class
    

    【讨论】:

    • 在不了解优先级和 Ruby 解析方式的情况下省略括号是自找麻烦。 Stack Overflow 有许多问题是由于人们放弃使用括号并遇到方法和块的问题。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-11-01
    • 1970-01-01
    相关资源
    最近更新 更多