Skip to content

Instantly share code, notes, and snippets.

@hiroshiro
Created February 28, 2014 12:33
Show Gist options
  • Save hiroshiro/fcdc30bee931b6e73ecf to your computer and use it in GitHub Desktop.
Save hiroshiro/fcdc30bee931b6e73ecf to your computer and use it in GitHub Desktop.
単に他のブロックに引数を渡すだけなら、ブロック引数を明示する。Rubyの構文。良い、悪い例。
require 'tempfile'
# bad
def with_tmp_dir
Dir.mktmpdir do |tmp_dir|
Dir.chdir(tmp_dir) { |dir| yield dir } # block just passes arguments
end
end
# good
def with_tmp_dir(&block)
Dir.mktmpdir do |tmp_dir|
Dir.chdir(tmp_dir, &block)
end
end
with_tmp_dir do |dir|
puts "dir is accessible as parameter and pwd is set: #{dir}"
end
@hiroshiro
Copy link
Author

単に他のブロックに引数を渡すだけのブロックリテラルを避けるため、 ブロック引数を明示することを検討しましょう。 ただしブロックが Proc に変換されることでのパフォーマンスに気をつけましょう。

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment