Why the following code produces different output for me?
<% @comments.each do |comment| %>
<%= comment.title %>
<% end %>
produces:
Title 1 title 2
but
<%= @comments.each { |comment| comment.title } %>
produces :
[#<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">]
This is because
<%= %>will print out the value returned by the block of code. In this case you have an enumerable@commentsthat you are calling each on. The methodeachwill return the enumerable that is used, in this case@comments.If you wanted to print out the collection of titles, you could use:
or more succinctly