I am trying to replace an array of names for a column of names out of a database. I am new to Ruby on rails so it could be something simple.
This works fine:
<% students = %w(John Paul Ringo George) %>
<% teams = RoundRobinTournament.schedule(students) %>
<td><%= teams %></td>
This i get an error:
<% @players.each do |player| %>
<% students = player.first_name %>
<% teams = RoundRobinTournament.schedule(students) %>
<td><%= teams %></td>
Error:
undefined method `delete_at' for "John":String
Did you mean? delete
delete!
In the RoundRobinModule the "delete_at" what causes the error:
require 'round_robin_tournament/version'
module RoundRobinTournament
def self.schedule(array)
array.push(nil) if array.size.odd?
n = array.size
1.step(n / 2, 1).each do |i|
array.insert(n - i, array.delete_at(i))
end
pivot = array.pop
games = (n - 1).times.map do
day = [[array.first, pivot]] (1...(n / 2)).map { |j| [array[j], array[n - 1 - j]] }
array.rotate!
day
end
array.push pivot unless pivot.nil?
games
end
end
CodePudding user response:
students
is supposed to be an array, yet students = player.first_name
makes it a string.
I don't know if this is want you want, but the following should work:
<% students = @players.pluck(:first_name) %> # or @players.map(&:first_name)
<% teams = RoundRobinTournament.schedule(students) %>
<td><%= teams %></td>
Use .pluck
if @players
holds an ActiveRecord::Relation
or .map
if it's an array of Player
objects.
But, the error tells you exactly what & where the problem is. You just need to pay attention. The would have crashed earlier but both String
and Array
respond to .size
.