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

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

使用 UTF-8 作为源文件编码。

    每个缩进级别使用两个 spaces (又名软 tabs). 不要硬 tabs

  # bad - four spaces
  def some_method
    do_something
  end

  # good
  def some_method
   do_something
  end

    使用 Unix-风格 换行符。(*BSD/Solaris/Linux/OSX 用户被为默认涵盖,Windows 用户必须特别小心.)

        n是换行,英文是LineFeed,ASCII码是0xA。         r是回车,英文是Carriage Return ,ASCII码是0xD。         windows下enter是 nr,unix下是n,mac下是r

        如果你正在使用 Git 你可能会想要添加下面的配置设置来保护你的项目(避免)Windows 蔓延过来的换行符:

 

  $ git config --global core.autocrlf true

    不用使用 ; 来分割语句和表达式。以此推论 - 一行使用一个表达式

  

 # bad
  puts 'foobar'; # superfluous semicolon

  puts 'foo'; puts 'bar' # two expression on the same line

  # good
  puts 'foobar'

  puts 'foo'
  puts 'bar'

  puts 'foo', 'bar' # this applies to puts in particular

    对于没有内容的类定义,尽可能使用单行类定义形式.

   

 # bad
  class FooError < StandardError
  end

  # okish
  class FooError < StandardError; end

  # good
  FooError = Class.new(StandardError)

    避免单行方法。即便还是会受到一些人的欢迎,这里还是会有一些古怪的语法用起来很容易犯错.
    无论如何 - 应该一行不超过一个单行方法.

    

# bad
  def too_much; something; something_else; end

  # okish - notice that the first ; is required
  def no_braces_method; body end

  # okish - notice that the second ; is optional
  def no_braces_method; body; end

  # okish - valid syntax, but no ; make it kind of hard to read
  def some_method() body end

  # good
  def some_method
   body
  end

    空方法是这个规则的例外。

  # good
  def no_op; end

    操作符旁的空格,在逗号,冒号和分号后;在 { 旁和在 } 之前,大多数空格可能对 Ruby 解释(代码)无关,但是它的恰当使用是让代码变得易读的关键。

  sum = 1 + 2
  a, b = 1, 2
  1 > 2 ? true : false; puts 'Hi'
  [1, 2, 3].each { |e| puts e }

    唯一的例外是当使用指数操作时:

  # bad
  e = M * c ** 2

  # good
  e = M * c**2

    { 和 } 值得额外的澄清,自从它们被用于 块 和 hash 字面量,以及以表达式的形式嵌入字符串。