I am new to ruby. I am trying to create a report_checker function that checks how often the word "green, red, amber" appears and returns it in the format: "Green: 2/nAmber: 1/nRed:1".
If the word is not one of the free mentioned, it is replaced with the word 'unaccounted' but the number of times it appears is still counted.
My code is returning repeats e.g if I give it the input report_checker("Green, Amber, Green"). It returns "Green: 2/nAmber: 1/nGreen: 2" as opposed to "Green: 2/nAmber: 1".
Also, it doesn't count the number of times an unaccounted word appears. Any guidance on where I am going wrong?
def report_checker(string)
array = []
grading = ["Green", "Amber", "Red"]
input = string.tr(',', ' ').split(" ")
input.each do |x|
if grading.include?(x)
array.push( "#{x}: #{input.count(x)}")
else
x = "Unaccounted"
array.push( "#{x}: #{input.count(x)}")
end
end
array.join("/n")
end
report_checker("Green, Amber, Green")
I tried pushing the words into separate words and returning the expected word with its count
"\n"for a newline, not a regular slash.array = input.map do |x|if you're collecting transformed versions. If you're doing counts,x.group_by(&:itself)can be a handy way of getting those.input & gradingwill give you that. This is case-sensitive, though.