This completely confused me for a while. I’m getting weird behaviour trying to loop through lines of text in erb, with the whole line of text being printed when the loop is complete.
<% "some\nmultiline\ntext".each_line do |line| %>
<%= line %> <br />
<% end %>
Outputs:
some
multiline
text
some multiline text
And so does:
<% "some\nmultiline\ntext".lines.each do |line| %>
<%= line %> <br />
<% end %>
But the following works as I would expect it to:
<% "some\nmultiline\ntext".lines.to_a.each do |line| %>
<%= line %> <br />
<% end %>
and prints:
some
multiline
text
I’m definitely not just putting in an = accidentally. What could be causing this strange behaviour?
I’m using Rails 3.0.10, Ruby 1.9.2.
I can’t say for sure but
"some\nmultiline\ntext".linesisEnumeratorand"some\nmultiline\ntext".lines.to_aisEnumerablethe big difference is that when you mix inEnumerablemodule to your class you have to defineeachmethod whose job it is toyield items to a supplied code block, one at a time. Enumerators are a recent and significant addition to Ruby. An enumerator is an object, not a method. An enumerator isn’t a container object. It has no “natural” basis for an each operation, the way an array does (start at element 0; yield it; go to element 1; yield it; and so on). The each iteration logic of every enumerator has to be explicitly specified.