What is the purpose of Ruby array's methods as

2020-08-23 01:22发布

问题:

I've read the documentation of the methods assoc and rassoc of Ruby array. I understand what they do. They both work on arrays of arrays. assoc returns the array whose first element equals the provided parameter, and rassoc does the same, but for the second element.

My question is what are these methods for? This functionality is very specific. I'm guessing there is some reason why these methods were created. what is it?

回答1:

There are a couple of reasons, but the main one is so that an Array can act like a Hash. I think that because Hashes are unsorted, the Ruby designers needed a way to represent a hash in an ordered fashion. I think that there are a lot of Enumerable methods that return arrays when invoked on a hash.