Conditional blocks in Ruby

ruby

Solution

if you are willing to specify argument with a block, it is possible.

given `with foo` above, you can write such snippet:

whatever = proc {puts "hello"}
#build a proc object with a block
if do_with_foo?
  with_foo &whatever
#pass it to with_foo
else
  whatever.call
#normally call it
end

Problem

Say I have function `with_foo` that takes a block, and wrap it around a piece of code, like ``` with_foo do puts "hello!" end ``` Now I would like to make the wrapping conditional, like ``` if do_with_foo? with_foo do puts "hello!" end else puts "hello!" # without foo end ``` Is there any way to write this shorter/more elegantly, meaning without having to repeat the code `puts "hello!"`?

Original source