Len
Len

Reputation: 2145

Rails prints string when each is used in html.erb

While it could of course be done neater by putting the code into the controller or something, I can not image why the following is happening: assume that @some_table.some_text contains 5 lines. putting the following code in my html.erb file:

<% @some_table.some_text.lines.each do |cur_line| %>
    foo
<% end %>

results in 5 foos followed by all the lines in @some_table.some_text. I could imagine this would happen when using the <%= %> but not with <% %>. Obviously, I don't want the @some_table.some_text to be shown.

What am I doing wrong here?

Upvotes: 2

Views: 1396

Answers (1)

Frankie Roberto
Frankie Roberto

Reputation: 1359

That's just the way that the Ruby lines method works - it returns an Enumerable, which can't be looped through in the same way. For your purposes, try

<% @some_table.some_text.split(/\n/).each do |cur_line| %>

instead.

Alternatively convert the Enemerable into an array before calling each, using one of the methods, eg:

<% @some_table.some_text.lines.collect.each do |cur_line| %>

Upvotes: 1

Related Questions