I've spent hours researching the subject and have tried many test sequences in IRB, and rails console but I'm just having trouble making headway into what is probably a very easy subject.
I understand arrays with at least 4 other languages but with Ruby I haven't found a mental connection with how I can assign variables to arrays..
Take for example:
def calculate_tsos(model, datavar, teamvar, valvar) var = model.compiled_this_week.find(:all) var.each_with_index do |rows, i| puts "#{model} [ Row #{i} | Team ID = #{rows.team_id} | Team = #{rows.team.name} | #{datavar} = #{rows.__send__(datavar)}" end end
This will give me:
TotalOffense [ Row 0 | Team ID = 5 | Team = Tulsa | ydspgm = 569.86 TotalOffense [ Row 1 | Team ID = 47 | Team = Houston | ydspgm = 562.77 TotalOffense [ Row 2 | Team ID = 20 | Team = Oklahoma | ydspgm =
547.86 etc. etc.So far, so good. I can at least see the data that I want.
Now, I want to assign the Team ID and the ydspgm to variables that I
can manipulate and use later on. Normally, I would think that I could do something like this:def calculate_tsos(model, datavar, teamvar, valvar) var = model.compiled_this_week.find(:all) var.each_with_index do |rows, i| teamvar[i] = rows.team.id valvar[i] = rows.__send__(datavar) puts "#{model} [ Row #{i} | Team ID = #{teamid[i]} | Team = #{rows.team.name} | #{datavar} = #{teamval[i]}" end end
But I get a..
undefined method `=' for 0:Fixnum
Down below you say you make this call and pass 'to_team_id' as the
argument to 'teamvar'. So teamvar is an integer... not array. Just
above you are trying to do "teamvar[i]". You can't do that on an
integer (which is what your error is trying to tell you).
If it were me I'd do this:
def calculate_tsos(model, datavar)
var = model.compiled_this_week.find(:all)
teamvar = # you need this so that the variable continues to exist
after the each_with_index block.
valvar = # same for this one.
var.each_with_index do |rows, i|
teamvar[i] = rows.team.id
valvar[i] = rows.__send__(datavar)
puts "#{model} [ Row #{i} | Team ID = #{teamid[i]} | Team =
#{rows.team.name} | #{datavar} = #{teamval[i]}"
end
[teamvar, valvar] #return the results
end
And then call it like this:
tv, vv = calculate_tsos(....)