Quoting Sam Dela Cruz <sam.dela.cruz / philips.com>: > Hi, > > I'm starting to use Ruby in one of my projects at work. I'm > coming from a > Perl background. > In my project I would need to parse a list of numbers (thousands > of them) > and then return the duplicates. In perl, I can do this: > > ##### Perl code > %hash = {}; > while (<>) > { > chomp; > $hash{$_}++; > } > > foreach my $key (sort keys %hash) > { > print "$key: $hash{$key}\n" if ($hash{$key} > 1); > } > > I tried to translate this in Ruby, but could not find en > equivalent of $hash{$_}++, this is auto increment. It also autovivifies the hash element, but Ruby doesn't have autovivification. Here's a nearly literal translation to Ruby (the main difference is that gets is like <STDIN>, not <>): hash = {} while gets chomp hash[$_] ||= 0 # vivify hash[$_] += 1 # increment end for key in hash.keys.sort print "#{key}: #{hash[key]}\n" if hash[key] > 1 end Here's the same thing in a slightly more Ruby-ish style ($_ is normally avoided in Ruby, even though it's available): hash = Hash.new( 0 ) $stdin.each do |line| hash[line.chomp] += 1 end hash.keys.sort.each do |key| puts "#{key}: #{hash[key]}" if hash[key] > 1 end Here, we create a hash whose default value for uninitialized elements is 0, rather than nil (nil is like Perl's undef). Note that a default value you provide this way is used directly for every element; it is not copied. Note also that line.chomp is not the same thing as chomp $line in Perl; line.chomp returns a new string rather than modifying the existing one. The exact equivalent of Perl's chomp $line would be line.chomp!. -mental