浅析Ruby的源代码布局及其编程风格

2019-09-25 09:40:05王冬梅

    在方法定义之间使用空行并且一个方法根据逻辑段来隔开。

   

 def some_method
   data = initialize(options)

   data.manipulate!

   data.result
  end

  def some_methods
   result
  end

    避免在一个方法调用的最后一个参数有逗号,特别是当参数不在另外一行。

   

 # bad - easier to move/add/remove parameters, but still not preferred
  some_method(
         size,
         count,
         color,
        )

  # bad
  some_method(size, count, color, )

  # good
  some_method(size, count, color)

    当给方法的参数赋默认值时,在 = 两边使用空格:

  

 # bad
  def some_method(arg1=:default, arg2=nil, arg3=[])
   # do something...
  end

  # good
  def some_method(arg1 = :default, arg2 = nil, arg3 = [])
   # do something...
  end

    虽然几本 Ruby 书建议用第一个风格,不过第二个风格在实践中更为常见(并可争议地可读性更高一点)。

    避免在不需要的时候使用行继续符 。实践中,
    除非用于连接字符串, 否则避免在任何情况下使用行继续符。

 

  # bad
  result = 1 - 
       2

  # good (but still ugly as hell)
  result = 1 
       - 2

  long_string = 'First part of the long string' 
         ' and second part of the long string'

    采用连贯的多行方法链式风格。在 Ruby 社区有两种受欢迎的风格,它们都被认为很好
    - . 开头(选项 A) 和 尾随 . (选项 B) 。

        (选项 A) 当一个链式方法调用需要在另一行继续时,将 . 放在第二行。

        

# bad - need to consult first line to understand second line
    one.two.three.
     four

    # good - it's immediately clear what's going on the second line
    one.two.three
     .four

        (选项 B) 当在另一行继续一个链式方法调用,将 . 放在第一行来识别要继续的表达式。

     

  # bad - need to read ahead to the second line to know that the chain continues
    one.two.three
     .four

    # good - it's immediately clear that the expression continues beyond the first line
    one.two.three.
     four

        在这里可以发现有关这两个另类风格的优点的讨论。

    如果一个方法调用的跨度超过了一行,对齐它们的参数。当参数对齐因为行宽限制而不合适,
    在第一行之后单缩进也是可以接受的。