Question

I'm confused about whether or not yield in Ruby and yield in Rails (specifically in views/templates) are the same entity or they're two different things which act differently depending on the context.

When I think about yield in Ruby, this usage comes to mind:

def some_method
  yield 123
end

some_method { |a| a + 1 } # => 124

When using ERB templates in Rails, though, yield is used to render the views specific to the current controller/action or to render content specified through provide or content_for.

Is this the same yield, or does the Rails version just happen to be different functionality with the same name?

Was it helpful?

Solution

It's the same thing. A block is passed to the layout method that will render the document body when called.

yield is actually a keyword in Ruby. It is possible to define a method named "yield" (Enumerator does this, for example), but whenever you see yield without a receiver, it will always be the same keyword that passes control to a block.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top