Occurrence Counter

Hi! I’m trying to make a code that opens a file, that basically contains
a bunch of numbers divided by space and adds those spaces to an array
and after that it transfers them to a hash where the occurrence is
counted, than sorted.
I probably made a mistake (or more), because the only thing my program
does is just shows all the numbers plus a 1…
Could anyone tell me where I went wrong?

numbers = Array.new

File.open (‘numbers.txt’) do |doc|
doc.each_line do |line|
numbers << line.split(" ")
end
end

counter = Hash.new(0)

numbers.each {|num| counter[num] += 1}

counter = counter.sort_by {|num, count| count}

counter.each {|num, count| puts “Nr. #{num} occured #{count} times”}

UPDATE: I tested the hash and the array with the print statement and I
think the problem is that somehow each number becomes a part of an array
that becomes part of another array so the hash only has 1 key and thats
the second array.
So numbers become [[1, 2, 3, 4]]… and I bet they are saved as strings
not integers.
How did that happen? :smiley:

On Sat, Nov 23, 2013 at 7:44 AM, Greg H. [email protected]
wrote:

numbers = Array.new

File.open (‘numbers.txt’) do |doc|
doc.each_line do |line|
nums = line.split(" ")

at this point, num is an array of “stringified” numbers

 numbers.push(nums)

at this point, you push the whole array of num

end
end

tip: do it slowly, one at at time. irb session is good enough w some
printout/debugging included. if this is for production code, much
better if you include tests…

best regards -botp

On Sat, Nov 23, 2013 at 12:44 AM, Greg H. removed_email[email protected]
wrote:

File.open (‘numbers.txt’) do |doc|
doc.each_line do |line|
nums = line.split(" ")
numbers.push(nums)

That does not match your description. You wrote “[…] and adds those
spaces to an array”. Here you are adding things between individual
spaces (probably those numbers you mention), not spaces.

end
end

counter = Hash.new(0)

numbers.each {|num| counter[num] += 1}

counter = counter.sort_by {|num, count| count}

You do not need the numbers Array - you can immediately count.

Assuming that you want to count occurrences of numbers, here’s how you
could do it:

counts = Hash.new 0

File.forach ‘numbers.txt’ do |line|
line.scan(/\d+/) {|num| counts[Integer(num)] += 1}
end

counts = counts.sort_by {|num, count| count}

Kind regards

robert

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs