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|
nums = line.split(" ")
numbers.push(nums)
end
end
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 7:44 AM, Greg Hajdu <lists@ruby-forum.com> wrote:
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|
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
···
On Sat, Nov 23, 2013 at 12:44 AM, Greg Hajdu <lists@ruby-forum.com> wrote: