John Smith
John Smith

Reputation: 6259

How to pass Proc as block with additional arguments?

Let's say, I have the following code:

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

How do I pass the block if it is given as a Proc? I tried:

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

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

But this gives me the error:

syntax error, unexpected '(', expecting keyword_end)

Upvotes: 0

Views: 37

Answers (1)

Eyeslandic
Eyeslandic

Reputation: 14900

Pass it as the last argument

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

Upvotes: 2

Related Questions