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

1 Answer 1

4

You could use tap:

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

myblock { 'my yield' }
# after yield
#=> my yield
Sign up to request clarification or add additional context in comments.

4 Comments

thanks thought there would be something more ruby elegant
was just typing that...you can use parens if you want to yield an argument (yield 5).tap { puts 'after yield' }.
@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.
@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| ... }

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.