2012-08-06 80 views
1

为什么下面的代码为我生成不同的输出?为什么“<%= @ comments.each {| comment | comment.title}%>”不会产生评论标题,而会产生“comment.inspect”...?

<% @comments.each do |comment| %> 
    <%= comment.title %> 
<% end %> 

生产:

Title 1 title 2 

<%= @comments.each { |comment| comment.title } %> 

生产:

[#<Comment id: 1, commentable_id: 1, commentable_type: "Entry", title: "Title 1", body: "bla", subject: "", user_id: 1, parent_id: nil, lft: 1, rgt: 2, created_at: "2012-07-31 06:15:26", updated_at: "2012-07-31 06:15:26">, #<Comment id: 2, commentable_id: 1, commentable_type: "Entry", title: "tile 2", body: "one more comment", subject: "", user_id: 1, parent_id: nil, lft: 3, rgt: 4, created_at: "2012-08-01 06:58:57", updated_at: "2012-08-01 06:58:57">] 

回答

4

这是因为<%= %>将打印出由代码块返回的值。在这种情况下,你有一个可调号码@comments,你打电话给每个人。方法each将返回使用的枚举值,在这种情况下为@comments

如果你想打印出标题的集合,你可以使用:

<%= @comments.map{ |comment| comment.title } %> 

或更简洁

<%= @comments.map(&:title) %> 
+0

我在哪里可以找到'&'在这方面的文件? – deefour 2012-08-06 14:48:26

+0

http://ruby-doc.org/core-1.9.3/Symbol.html#method-i-to_proc – 2012-08-06 14:57:00

+0

非常感谢! – deefour 2012-08-06 14:57:18

相关问题