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

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

    对于 hash 字面量两种风格是可以接受的。

  # good - space after { and before }
  { one: 1, two: 2 }

  # good - no space after { and before }
  {one: 1, two: 2}

    第一种稍微更具可读性(并且争议的是一般在 Ruby 社区里面更受欢迎)。
    第二种可以增加了 块 和 hash 可视化的差异。
    无论你选哪一种都行 - 但是最好保持一致。

    目前对于嵌入表达式,也有两个选择:

  # good - no spaces
  "string#{expr}"

  # ok - arguably more readable
  "string#{ expr }"

    第一种风格极为流行并且通常建议你与之靠拢。第二种,在另一方面,(有争议)更具可读性。
    如同 hash - 选取一个风格并且保持一致。

    没有空格 (, [之后或者 ], )之前。

 

  some(arg).other
  [1, 2, 3].length

  ! 之后没有空格 .

  # bad
  ! something

  # good
  !something

    when和case 缩进深度一致。我知道很多人会不同意这点,但是它是"The Ruby Programming Language" 和 "Programming Ruby"中公认的风格。

    

# bad
  case
   when song.name == 'Misty'
    puts 'Not again!'
   when song.duration > 120
    puts 'Too long!'
   when Time.now.hour > 21
    puts "It's too late"
   else
    song.play
  end

  # good
  case
  when song.name == 'Misty'
   puts 'Not again!'
  when song.duration > 120
   puts 'Too long!'
  when Time.now.hour > 21
   puts "It's too late"
  else
   song.play
  end

  case
  when song.name == 'Misty'
   puts 'Not again!'
  when song.duraton > 120
   puts 'Too long!'
  when Time.now > 21
   puts "It's too late"
  else
   song.play
  end

    当赋值一个条件表达式的结果给一个变量时,保持分支的缩排在同一层。

 

  # bad - pretty convoluted
  kind = case year
  when 1850..1889 then 'Blues'
  when 1890..1909 then 'Ragtime'
  when 1910..1929 then 'New Orleans Jazz'
  when 1930..1939 then 'Swing'
  when 1940..1950 then 'Bebop'
  else 'Jazz'
  end

  result = if some_cond
   calc_something
  else
   calc_something_else
  end

  # good - it's apparent what's going on
  kind = case year
      when 1850..1889 then 'Blues'
      when 1890..1909 then 'Ragtime'
      when 1910..1929 then 'New Orleans Jazz'
      when 1930..1939 then 'Swing'
      when 1940..1950 then 'Bebop'
      else 'Jazz'
      end

  result = if some_cond
        calc_something
       else
        calc_something_else
       end

  # good (and a bit more width efficient)
  kind =
   case year
   when 1850..1889 then 'Blues'
   when 1890..1909 then 'Ragtime'
   when 1910..1929 then 'New Orleans Jazz'
   when 1930..1939 then 'Swing'
   when 1940..1950 then 'Bebop'
   else 'Jazz'
   end

  result =
   if some_cond
    calc_something
   else
    calc_something_else
   end