Saw this piece of code in a Ruby on Rails book. This first one is from a view and the second one is a helper module. I don't understand how that &block
and the attributes={}
thing work. Can anyone guide me to a tutorial of some kind explaining this?
<% hidden_div_if(@cart.items.empty?, :id => "cart") do %>
<%= render(:partial => "cart", :object => @cart) %>
<% end %>
module StoreHelper
def hidden_div_if(condition, attributes = {}, &block)
if condition
attributes["style"] = "display: none"
end
content_tag("div", attributes, &block)
end
end
Best Answer
Blocks are a fairly basic part of ruby. They're delimited by either
do |arg0,arg1| ... end
or{ |arg0,arg1,arg2| ... }
.They allow you to specify a callback to pass to a method. This callback can be invoked two ways - either by capturing it by specifying a final argument prefixed with
&
, or by using theyield
keyword:Note that our callback was the same in each case - we can remove repetition by saving our callback in an object, and then passing it to each method. This can be done using
lambda
to capture the callback in an object, and then passed to a method by prefixing it with&
.It's important to understand the different uses of
&
here as a prefix to the last argument of a functionIf you look around blocks are used all over the place, especially in iterators, like
Array#each
.