String iteration using each_line
I have the following code which displays instructions in an ordered list. When it's rendered in the browser, it outputs all of the instructions at the end in a single line. Am I doing something wrong? See output below for example.
Code:
<% @recipe.instructions.each_line do |instruction| %>
<li><%= instruction %></li>
<% end %>
Output:
<p>
<b>Instructions:</b>
<ol>
<li>Roast garlic
</li>
<li>test
</li>
<li>eat icecream</li>
Roast garlic
test
eat icecream 开发者_如何学Go </ol>
</p>
Rails 3 rc2 ruby 1.9.2dev (2010-07-11 revision 28618)
Are you sure you aren't doing something like this instead?
<%= @recipe.instructions.each_line do |instruction| %>
<li><%= instruction %></li>
<% end %>
Note the extra = at the beginning of the loop. Since each_line returns the string, it'll spit the string out again.
So I finally figured this out. I changed the code to use Array#each and removed the equal sign in the block helper.
Final code:
<% @recipe.instructions.split(/\r\n/).each do |instruction| %>
<li><%= instruction %></li>
<% end %>
精彩评论