6

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

I always thought that the following are just two ways of saying the same thing:

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

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

But I'm getting some weird behaviour in one of my ERB templates where the two syntaxes seem to do two different things. This code works great:

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

But when I re-write it as:

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

... I just end up with a concatenated string of my @menu items. Am I missing something? Is there some tiny grain of syntactic sugar getting in the way here?

Community
  • 1
  • 1
Matt Zukowski
  • 4,469
  • 4
  • 37
  • 38
  • 3
    This is a duplicate of [Ruby Block Syntax Error](http://StackOverflow.Com/q/6854283/), [Code block passed to `each` works with brackets but not with `do`-`end` (ruby)](http://StackOverflow.Com/q/6718340/), [Block definition - difference between braces and `do`-`end` ?](http://StackOverflow.Com/q/6179442/), [Ruby multiline block without `do` `end`](http://StackOverflow.Com/q/3680097/), [Using `do` block vs brackets `{}`](http://StackOverflow.Com/q/2122380/), [What is the difference or value of these block coding styles in Ruby?](http://StackOverflow.Com/q/533008/) … – Jörg W Mittag Sep 20 '11 at 15:28
  • 2
    … and [Ruby block and unparenthesized arguments](http://StackOverflow.Com/q/420147/). – Jörg W Mittag Sep 20 '11 at 15:28
  • Ack! Now I'm torn. To delete or not to delete? With 4 upvotes, maybe my wording is useful to someone? – Matt Zukowski Sep 20 '11 at 15:42
  • @Matt, it is a duplicate, but there's no need to delete. – Matthew Flaschen Sep 20 '11 at 16:15

1 Answers1

0

I would use your first method or place this code in a view helper. But if I did want to use blocks I'd probably do something like this.

<% @menu.collect do |m| %>
   <%= content_tag("li") do %>
        <% link_to(m.capitalize, url_for(:controller => m)) %>
   <% end %>
<% end %>
jspooner
  • 10,975
  • 11
  • 58
  • 81