Gangmax Blog

The 'sort' method of 'Hash' in Ruby

When I wanted to make a hash instance’s content be sorted by key’s dictionary order, I found a problem.

1
2
3
4
5
6
7
8
9
10
11
12
h.keys.sort.each do |key|
value = h[key]
...
end

# The interpreter complains that "h has no keys method defined as an Array type", but the following code was working:

h.each do |key, value|
...
end

# Which confused me: if h is not Hash type, why the code worked?

Also as I know from the Ruby document, Hash has no sort method defined. Then I made a test:

1
2
3
4
5
6
7
8
9
> h = {'x' =>1, 'b'=>2, 'c'=> 3}
=> {"x"=>1, "b"=>2, "c"=>3}
> h.sort
=> [["b", 2], ["c", 3], ["x", 1]]
> a.each { |k, v| puts "#{k}=#{v}"}
b=2
c=3
x=1
=> [["b", 2], ["c", 3], ["x", 1]]

This is the reason why h is an Array instance instead of a Hash instance but it worked, because I found the code has a line “h = h_old.sort” above which defined “h”. So, “h_old” is a Hash instance but “h” is NOT! However you can still use the “each” method in a Hash way on “h” although it’s an Array instance.

But I still don’t understand why the Ruby document does not have the “sort” method for “Hash” class.

Comments