0

I want to return the output of yield but also execute the code after yield, is there a more "right" way?:

def myblock
  yield_output = yield
  puts 'after yield'
  yield_output
end

myblock {'my yield'}
# after yield
#  => my yield
joshweir
  • 5,427
  • 3
  • 39
  • 59

1 Answers1

4

You could use tap:

def myblock
  yield.tap { puts 'after yield' }
end

myblock { 'my yield' }
# after yield
#=> my yield
Stefan
  • 109,145
  • 14
  • 143
  • 218
  • thanks thought there would be something more ruby elegant – joshweir Aug 03 '17 at 09:45
  • 1
    was just typing that...you can use parens if you want to yield an argument `(yield 5).tap { puts 'after yield' }`. – Simple Lime Aug 03 '17 at 09:45
  • 1
    @SimpleLime although `yield` is not a method, I'd put the parentheses around the argument(s), i.e. `yield(5).tap { ... }`, but either way works. – Stefan Aug 03 '17 at 09:50
  • 3
    @joshweir in case you need the result (`'my yield'`) in your code: `tap` passes the receiver to the block, so you can write `yield.tap { |result| ... }` – Stefan Aug 03 '17 at 09:55