Christopher Oezbek
Christopher Oezbek

Reputation: 26493

Ruby: How to call a method with a proc instead of a block

I have a method that requires a block, but I just have a Proc object. How can I call it without ugly wrapping?

def twice
  yield
  yield
end

p = Proc.new { puts "Hello" }

twice p          # Does not compile "wrong number of parameters"
twice { p.call } # Ugly and difficult for additional parameters

Upvotes: 3

Views: 147

Answers (1)

Andrey Deineko
Andrey Deineko

Reputation: 52377

You can convert the proc to a block using unary ampersand (&):

twice &p
# Hello
# Hello
#=> nil

Upvotes: 5

Related Questions