[Solved] 2D Array being used as hash, confused


#1

In the Ruby Language, why am I able to treat an array of 2 element arrays as a hash? In exercise 5, the instructions say that the sort_by method creates a 2D array, however, Ruby doesn't complain when I treat such a 2D array as a hash.

tl;dr, both solutions below are acceptable for task 7 and I don't know why:

Hash version:
puts "your input please:"
text = gets.chomp
words = text.split
frequencies = Hash.new(0)
words.each do |x| frequencies[x]+=1 end
frequencies = frequencies.sort_by do |x,y| y end
frequencies.reverse!
frequencies.each{|a, b| puts a + " " + b.to_s}

Array version:
puts "your input please:"
text = gets.chomp
words = text.split
frequencies = Hash.new(0)
words.each do |x| frequencies[x]+=1 end
frequencies = frequencies.sort_by do |x,y| y end
frequencies.reverse!
frequencies.each{|a| puts a[0] + " " + a[1].to_s}

Can anyone shed some insight? Thanks!


#2

What is not obvious at first is that frequencies may start out as a hash, but it gets overwritten by the array of tuples created by sort_by.


#3

I see. So this means that I can use |a,b| in both hashes and arrays. Thanks!