首页 > 解决方案 > 如何将 Proc 作为带有附加参数的块传递?

问题描述

假设,我有以下代码:

File.open("text.txt", "w") do |f|
  f << "hello"
end

如果它作为 Proc 给出,我如何通过该块? 我试过了:

log_to_file = Proc.new { |f| f << "hello"}

File.open("text.txt", "w")(&log_to_file)

但这给了我错误:

syntax error, unexpected '(', expecting keyword_end)

标签: ruby-on-railsruby

解决方案


将其作为最后一个参数传递

File.open("text.txt", "w", &log_to_file)

推荐阅读