Reputation: 22044
This is question is added to my last one.
The problem in my last question was solved by changing the following code:
<p><%= each(2,16,3){|x| x } %></p>
to
<p>
<% each(2,16,3) do |x| %>
<%= x %>
<% end %>
<p>
But I still don't know the difference between the one line style delimited by {} and 3 lines styles by using do and end tag
Upvotes: 1
Views: 86
Reputation: 159095
The first version:
<p><%= each(2,16,3){|x| x } %></p>
takes the return value of the entire each
method call and tries to output it. The second version:
<p>
<% each(2,16,3) do |x| %>
<%= x %>
<% end %>
<p>
takes each individual item one at a time and outputs it (since you are evaluating the output inside the block). The actual return value of the each
method is not used.
As mentioned by others, this only matters when you need to do some sort of output/calculation inside the block, which each value yield
ed to the block; the rest is just semantics. The following are the same:
evens = (0..10).to_a.delete_if { |value| value.odd? }
and
evens = (0..10).to_a.delete_if do |value|
value.odd?
end
Upvotes: 3