Absolute RoR newbie here, I’m trying to render out multiple leagues in a loop, incrementing the div_# each time, here’s a cut down version, without the html. It works when I hard code div_1 or div_2 to be sorted, but div_name doesn’t work, even though it has the right contents I need it to be seen as the array.
<% div_1 = Array.new
div_1 << { :Name => 'Rob', :Played => '2', :Won => '1', :Lost => 1, :Points => 4}
div_2 = Array.new
div_2 << { :Name => 'Gavin', :Played => '2', :Won => '1', :Lost => 1, :Points => 4}
for i in (1..2)
i = i.to_s
div_name = "div_" + i
div_name.sort_by { |position| position[:Points] }.reverse!.each do |position| %>
<%= position[:Name] %>
There are lots of problems here:
div_1is now an array with a single element, which is a hash. You don’t need an array if you’ll just have one element in it.Where’s the block for this loop? After that statement,
iis still undefined, so when you callyou’ll get a NameError.
Even if
i == 1,div_namewill be a string with value ‘div_1’, and not a copy or instance of thediv_1variable you define above.Now you’re trying to call
sort_byon a string, which doesn’t respond to that, because it doesn’t make sense.You don’t have a variable named
positiondefined at this scope.Also, when you find yourself putting lots of logic inside of a view within
<% %>tags, that’s a sign that you need to move that code elsewhere, like to the controller. You could define and calculate@positionsas an array of hashes in the controller, and then in the view do something like: