Skip to content

Instantly share code, notes, and snippets.

@frankel
Last active December 10, 2015 04:08
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save frankel/4378901 to your computer and use it in GitHub Desktop.
Save frankel/4378901 to your computer and use it in GitHub Desktop.
ruby style guide
Ruby 1.9 偏好使用新的 lambda 字面语法。
# 差
lambda = lambda { |a, b​​| a + b }
lambda.call(1, 2)
# 好
lambda = ->(a, b) { a + b }
lambda.(1, 2)
============================================
通过 contingency 方法 (一个由 Avdi Grimm 创造的词)来减少 begin 区块的使用。
# 差
begin
something_that_might_fail
rescue IOError
# handle IOError
end
begin
something_else_that_might_fail
rescue IOError
# handle IOError
end
# 好
def with_io_error_handling
yield
rescue IOError
# handle IOError
end
with_io_error_handling { something_that_might_fail }
with_io_error_handling { something_else_that_might_fail }
============================================
在处理需要出现的哈希键时,使用fetch 。
heroes = { 蝙蝠侠: 'Bruce Wayne', 超人: 'Clark Kent' }
# 差劲- 如果我们打错字的话,我们就无法找到对的英雄了
heroes[:蝙蝠侠] # => "Bruce Wayne"
heroes[:超女] # => nil
# 好 - fetch 会抛出一个 KeyError 来体现这个问题
heroes.fetch(:supermann)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment