Why are do / end and {} always equivalent?

Possible duplicate:
Ruby block and unparenthesized arguments
What is the difference or meaning of these block coding styles in Ruby?

I always thought that the following two ways to say the same thing:

[1,2,3].collect{|i| i * 2} [1,2,3].collect do |i| i * 2 end 

But I get some weird behavior in one of my ERB templates where the two syntaxes seem to do two different things. This code works fine:

 <%=raw @menu.collect { |m| content_tag("li") { link_to(m.capitalize, url_for(:controller => m)) } } %> 

But when I rewrite it as:

 <%=raw @menu.collect do |m| content_tag("li") do link_to(m.capitalize, url_for(:controller => m)) end end %> 

... I just ended up with a concatenated string of my @menu elements. Am I missing something? Is there a little tiny grain of syntactic sugar here?

+6
source share
1 answer

I would use your first method or put this code in a view helper. But if I wanted to use blocks, I would probably do something like this.

 <% @menu.collect do |m| %> <%= content_tag("li") do %> <% link_to(m.capitalize, url_for(:controller => m)) %> <% end %> <% end %> 
0
source

Source: https://habr.com/ru/post/897693/


All Articles