jeudi 25 février 2016

Ruby: Iterating Over Array Based on Following Elements

I am creating a week-by-week report of meetings using Ruby. I have a large array that contains the names of the meetings and I have duplicated the elements based on how many weeks they occured.

Example:

meetingsArray = [..., "boardInvestorsMeeting", "clientMeeting", "clientMeeting", "clientMeeting", "waterCoolerChat", "waterCoolerChat",  "waterCoolerChat", "waterCoolerChat",...]

where ... represents a finite set of elements.

Code snippet:

for m in meetingsArray[m.to_i]
  if (meetingsArray[m.to_i] === meetingsArray[(m.to_i) + 1] && meetingsArray[m.to_i] === meetingsArray[(m.to_i) + 2] && meetingsArray[m.to_i] === meetingsArray[(m.to_i) + 3])
    puts "Week of the 1st: " + "#{meetingsArray[m.to_i].inject{|a| a}}"
  elsif (meetingsArray[m.to_i] === meetingsArray[(m.to_i) + 1] && meetingsArray[m.to_i] === meetingsArray[(m.to_i) + 2])
    puts "Week of the 8th: " + "#{meetingsArray[m.to_i].inject{|a| a}}"
  elsif (meetingsArray[m.to_i] === meetingsArray[(m.to_i) + 1])
    puts "Week of the 15th: " + "#{meetingsArray[m.to_i].inject{|a| a}}"
  else
    puts "Week of the 22nd: " + "#{meetingsArray[m.to_i].inject{|a| a}}"
  end
end

So for our example above, I would like the expected output to be:

.
.
.
Week of the 1st: boardInvestorsMeeting
Week of the 1st: clientMeeting
Week of the 8th: clientMeeting
Week of the 15th: clientMeeting
Week of the 1st: waterCoolerChat
Week of the 8th: waterCoolerChat
Week of the 15th: waterCoolerChat
Week of the 22nd: waterCoolerChat
.
.
.

where

.
.
.

again represents a countable set of elements.

Note that "clientMeeting" has "Week of the 1st:" then "Week of the 8th:" then "Week of the 15th:" in front of it because is repeated twice; while "boardInvestorsMeeting" only has "Week of the 1st:" in front of it because it isn't repeated and only appears in meetingsArray once.

Where I'm stuck:

The code snippet above doesn't yield the expected output above. Instead, it gives me:

Week of the 22nd: boardInvestorsMeeting

as the only output.

That's it. One line.

Note that "boardInvestorsMeeting" is the twelfth element in the meetingsArray.

What am I missing?

Aucun commentaire:

Enregistrer un commentaire