Problem about "each" in rails

CODE1:

<% @posts.each do |p|%>
  <%=h p.name %>
<% end %>

this will show the name string like "Tom" in the web page.

CODE2:

<%=h @posts.each {|p| p.name} %>

why this code return serial strings like #<Post:0x3a893e8> ?

Because you're outputting the return value of the whole loop, not the
output of each block.
If you run that command in your console, you will see it return an
array of Posts; and that's what you're trying to render.

If you want the names seperated by comma, try this:

<%=h @posts.map{|p| p.name}.join(', ') %>

Or more concisely (because it's fun):
<%=h @posts.map(&:name).to_sentence %>
which will make it "Tom, Dick, and Harry".

Michael Pavling wrote:

Adam Stegman wrote:

Or more concisely (because it's fun):
<%=h @posts.map(&:name).to_sentence %>
which will make it "Tom, Dick, and Harry".

I'm newbie,can't understand "(&:name)",but i know this code is skillful.

Grick Zh wrote:

Adam Stegman wrote:

Or more concisely (because it's fun):
<%=h @posts.map(&:name).to_sentence %>
which will make it "Tom, Dick, and Harry".

1) @posts.map
This will return a new enumerable, replacing each element of @posts with
whatever the block says
2) &:name
Shortcut to indicate a block and a method. In this case, the method is
:name (post.name)

Other example: [1,2,3,4].inject(:+) # Sum every element of the array.
Will of course fail if an element does not understand "+".

3) to_sentence
We now have an array with names. "to_sentence" is, I believe, an
activesupport method which joins the array into a string with commas,
and adds "and " between the second to last and last item.