my objective is to read a txt.file, and split the contents into an array. However I am having issue with the split command.
My text file content is this
Acosta,1,3,0,0,0
Amezcua,2,1,2,0,2
Avalos,0,1,1,0,0
My code is this
file = open("score2.txt", "r")
file.each do |line|
array = line.split(",")
print array
end
However my powershell returns this
["Acosta", "1", "3", "0", "0", "0\n"]["Amezcua", "2", "1", "2", "0", "2\n"]["Avalos", "0", "1", "1", "0", "0\n"]["\n"]
I am confused with what I get from the powershell output. Firstly my txt only contains three lines, why is it that powershell prints out 4 array instead of 3?. Secondly, why is that the element of every last array contains \n, I don't want that. Thirdly if I replaced print with puts, I wouldn't have the issue of \n on every last element of the arrays; why is that so?
To add on, I will explain the reason why I want to remove \n from the last element of the array. The numbers in txt document represents placing of an individual in a tournament whereby e.g. Acosta,1,3,0,0,0 means Acosta scored the first placed in the first match, third in the second match, and no placing in the remaining matches. Hence I want to assign a point system based on the placing each individual scored and finally printing out the total score of each person.
Therefore I used an ifelsif sequence to assign the score as follow
file = open("score2.txt", "r")
file.each do |line|
array = line.split(",")
name = array.shift
score = 0
array.each do |placing|
if placing == "1"
score += 6
elsif placing == "2"
score += 4
elsif placing == "3"
score += 2
else
score = score
end
end
print "#{name}: #{score} "
end
However due to \n in the last element of an array, I am unable to assign points to the last match of the tournament. Hence I want to remove the \n from the last element of the arrays.
This exercise is from http://www.evc-cit.info/cit020/beginning-programming/chp_05/exercises2.html.
Can someone kindly enlighten me? Thank you