ruby-on-rails - 如何将 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)
解决方案
将其作为最后一个参数传递
File.open("text.txt", "w", &log_to_file)
推荐阅读
- c++ - SDL2:在 16 x 16 网格上平滑移动
- azure - 超时已过期 - 将数据从托管实例移动到 DataWarehouse AZure 数据工厂
- notepad++ - 查找和修改文本
- python - 如何传输 pygobject3 以与 PyCharm 一起使用
- airflow - 气流信号 SIGTERM
- c# - 如何获取特定类型 C#、XML、LINQtoXML 的最后一个 XElement
- css - 继承 CSS 变量,或回退到默认值
- javascript - 根据点击 JavaScript 更改评分类型
- java - 如何避免排序字符串数组中的重复值?
- javascript - 将“密码”类型添加到 Google 驱动器中的 Google Apps 脚本输入框添加