Rails 5 - rendering array defined in application_helper.rb

51 views Asked by At

I want to use nhl_scores gem to get and display recent NHL game scores on the page. This is how I defined the method in app/helpers/application_helper.rb:

def scores
    games = NHLScores::Games.new
    s = []
    games.recent.each do |g|
        s.push("#{g.away_team} @ #{g.home_team} - #{g.away_team_score}:#{g.home_team_score}")
    end
    s
end

And this is how I display this array:

<ul>
    <%= scores.each do |s| %>
        <li><%= s %></li>
    <% end %>
</ul>

The result is:

pic with result

Yeah, for some reason the full array gets displayed after the last closing li tag but before the closing ul tag. How do I remove it? Should I define the method that returns this array elsewhere?

2

There are 2 answers

0
Alok Swain On BEST ANSWER

Try this

<ul>
    <% scores.each do |s| %>
        <li><%= s %></li>
    <% end %>
</ul>

The <%= %> is displaying the entire scores array again which you dont want(<%= %> causes the value to be displayed).

0
user229044 On

Don't use <%= to output the result of scores.each, which is scores.

You're outputting the <li> tags inside the .each block, and then when the .each is done, the value returned from each (scores) is being passed to <%= which echos it to the browser.

You need to be aware of when to use <% and <%=; in this case, you need <%.