views:

36

answers:

3

Sorry, I don't really know how to title this question.

Here's my code in view:

<% country.cities.each_with_index do |city, i| %>
  <% city.shops.each do |shop| %>
    <%=h shop.name.join(", ") %>
  <% end %>
<% end %>

So in this city, let's say there are three shops: Walmart, Ace Hardware, Harman Kardon.

The result of the above code would yield:

Walmart Ace Hardware Harman Kardon

How do I join each of them with ", "?

I tried <%= shop.name.join(", ") %> but not permitted. Error.

Thanks. I love Stack Overflow community. You guys have been more, much more than awesome!

EDIT

I just noticed something. Walmart is in City A; Ace HArdware and Harman Kardon are in City B. That is why it joined city by city.

+4  A: 

The code:

<%= shop.name.join(", ") %>

Won't work, because you are already inside the block, and join is a method specific to enumerables, where at this point you just have whatever object.

What you want here is actually:

<%= city.spots.map { |shop| shop.name }.join(", ") %>

The reason this works is because:

city.spots.map { |shop| shop.name }

Will give you an array of the names of all of the shops, which you can then join using the string of your choice.

You may also want to make sure you html escape the names (just in case):

<%= h( city.spots.map { |shop| shop.name }.join(", ") ) %>

EDIT:

As injekt pointed out, and for the purposes of completeness, you can also abuse Symbol#to_proc and use:

<%= city.spots.map(&:name).join(", ") %>

EDIT PART2:

Now that we have the new surrounding block, we need to re-write the expression:

<%= h( country.cities.map { |city| city.shops }.flatten.map { |shop| shop.name }.join(", ") ) %>
TreyE
injekt
Actually, Symbol#to_proc is part of active support for rails < 3 in ruby 1.8.6/7, so it's available. The main problem is I didn't want to clutter up the answer with syntactic trickery; but I'll add the example just for completeness.
TreyE
Ah I wasn't aware of ActiveSupport supporting this. Interesting, and no, I agree I wouldn't have used it as an official answer either.
injekt
The interesting thing is ActiveSupport was the original source, it was later made part of core ruby.
TreyE
I'm sorry guys, TreyE works but the result is: Walmart, Ace Hardware Harmen Kardon. Notice the "Harman Kardon" wasn't joined with ", ". Probably because I left out the earlier code. Please check my edited code. Thanks.
Victor
Fantastic! TreyE and injekt, thank you so much! You guys rock!
Victor
A: 

Try this !

<% c = [] %>
<% city.spots.each do |shop| %>
  <% c << shop.name %>
  <%= shop.name %>
<% end %>
krunal shah
A: 

Instead of looping over the names you need to join the elements together

<% city.spots.join(', ') %>

should work assuming city.spots is an Array, otherwise you need .map as TreyE used.

Chris Hulan