From: James Edward Gray II Date: 2005-12-10T06:14:49+09:00 Subject: Re: new to Ruby - pls help in translating this On Dec 9, 2005, at 3:02 PM, mental@rydia.net wrote: > Quoting Sam Dela Cruz : > >> Here's what I decided on using (looks more like what I originally >> posted in perl): >> >> hash = Hash.new(0) >> File.open(ARGV[0],"r").each do |line| >> hash[line.chomp] += 1 >> end >> >> hash.keys.sort.each do |key| >> puts "#{key}: #{hash[key]}" if hash[key] > 1 >> end > > One caution here -- if you want the file handle to be closed when > you are finished, you must do either: > > stream = File.open(ARGV[0],"r") > stream.each do |line| > hash[line.chomp] += 1 > end > stream.close > > or (this is often better because it will automatically close the > handle even if there's an exception): > > File.open(ARGV[0],"r") do |stream| > stream.each do |line| > hash[line.chomp] += 1 > end > end Or: File.foreach(ARGV.first) do |line| # ... end James Edward Gray II