Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@jlecour
Last active October 14, 2015 08:19
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jlecour/7ff6de9ff14ca6b2cc36 to your computer and use it in GitHub Desktop.
Save jlecour/7ff6de9ff14ca6b2cc36 to your computer and use it in GitHub Desktop.
Is there a better way to have a first method (`prelude` here) accept an optional block, pass it to another method (`final` here) and have it yielded in the end, without having to yield also in the first method ?
def prelude
if block_given?
final { |name|
yield(name)
}
else
final
end
end
def final
if block_given?
yield("world")
else
puts "- no block given to #final"
end
end
puts "# prelude with no block"
prelude
puts ""
puts "# prelude with a block"
prelude { |name|
puts "Hello #{name} from prelude block"
}
@jlecour
Copy link
Author

jlecour commented Oct 14, 2015

Thanks to @jjaffeux for the solution :

def prelude(&block)
  final(&block)
end

I'va previously tried that, but forgot to put the & also when calling final(&block) so the block was passed without being converted to a Proc (or something like this).

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment