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 ?
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 ?
On 18 March 2010 16:33, Grick Zh [email protected] wrote:
<%=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(’, ') %>
Michael P. wrote:
On 18 March 2010 16:33, Grick Zh [email protected] wrote:
<%=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.
I got it,thanks for your help
Adam S. 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.
Or more concisely (because it’s fun):
<%=h @posts.map(&:name).to_sentence %>
which will make it “Tom, Dick, and Harry”.
Grick Zh wrote:
Adam S. wrote:
Or more concisely (because it’s fun):
<%=h @posts.map(&:name).to_sentence %>
which will make it “Tom, Dick, and Harry”.
Other example: [1,2,3,4].inject(:+) # Sum every element of the array.
Will of course fail if an element does not understand “+”.
This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.
Sponsor our Newsletter | Privacy Policy | Terms of Service | Remote Ruby Jobs