Ruby编程中的语法使用风格推荐

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

    

# bad
  unless success?
   puts 'failure'
  else
   puts 'success'
  end

  # good
  if success?
   puts 'success'
  else
   puts 'failure'
  end

    不用使用括号包含 if/unless/while 的条件。

 

  # bad
  if (x > 10)
   # body omitted
  end

  # good
  if x > 10
   # body omitted
  end

    在多行 while/until 中不要使用 while/until condition do 。

   

 # bad
  while x > 5 do
   # body omitted
  end

  until x > 5 do
   # body omitted
  end

  # good
  while x > 5
   # body omitted
  end

  until x > 5
   # body omitted
  end

    当你有单行主体时,尽量使用 while/until 修饰符。

  # bad
  while some_condition
   do_something
  end

  # good
  do_something while some_condition

    否定条件判断尽量使用 until 而不是 while 。

  

 # bad
  do_something while !some_condition

  # good
  do_something until some_condition

    循环后条件判断使用 Kernel#loop 和 break,而不是 begin/end/until 或者 begin/end/while。

  

 # bad
  begin
   puts val
   val += 1
  end while val < 0

  # good
  loop do
   puts val
   val += 1
   break unless val < 0
  end

    忽略围绕内部 DSL 方法参数的括号 (如:Rake, Rails, RSpec),Ruby 中带有 "关键字" 状态的方法(如:attr_reader,puts)以及属性存取方法。所有其他的方法调用使用括号围绕参数。

    

class Person
   attr_reader :name, :age

   # omitted
  end

  temperance = Person.new('Temperance', 30)
  temperance.name

  puts temperance.age

  x = Math.sin(y)
  array.delete(e)

  bowling.score.should == 0

    忽略隐式选项 hash 外部的花括号。

  

 # bad
  user.set({ name: 'John', age: 45, permissions: { read: true } })

  # good
  user.set(name: 'John', age: 45, permissions: { read: true })

    内部 DSL 方法的外部括号和大括号。

  class Person < ActiveRecord::Base
   # bad
   validates(:name, { presence: true, length: { within: 1..10 } })

   # good
   validates :name, presence: true, length: { within: 1..10 }
  end

    方法调用不需要参数,那么忽略圆括号。

 

  # bad
  Kernel.exit!()
  2.even?()
  fork()
  'test'.upcase()

  # good
  Kernel.exit!
  2.even?
  fork
  'test'.upcase

    在单行代码块的时候宁愿使用 {...} 而不是 do...end。避免在多行代码块使用 {...} (多行链式通常变得非常丑陋)。通常使用 do...end 来做 流程控制 和 方法定义 (例如 在 Rakefiles 和某些 DSLs 中)。避免在链式调用中使用 do...end。