Martin Malmstrøm
Martin Malmstrøm

Reputation: 95

Compare hash values with corresponding array values in Ruby

I've scripted my way into a corner where I now need to compare the values of a hash to the corresponding element in an array.

I have two "lists" of the same values, sorted in different ways, and they should be identical. The interesting part is when they don't, so I need to identify those cases. So basically I need to check whether the first value of the first key-value pair in the hash is identical to the first element of the array, and likewise the second value checked towards the second element and so on for the entire set of values in the hash.

I'm sort of new to Ruby scripting, but though this should be easy enough, but alas....

Upvotes: 2

Views: 1336

Answers (2)

Arkhitech
Arkhitech

Reputation: 475

Technically speaking, hash is not guaranteed to ordered, so your assumption of matching the value at 'each' index of hash may not always hold true. However, for sake of answering your question, assuming h is your hash, and a is your array:

list_matches = true
h.values.each_with_index {|v, i| list_matches = list_matches && a[i] == v}

if list_matches is not equal to true than that is where the the items in the two collections don't match.

Upvotes: 0

mu is too short
mu is too short

Reputation: 434665

Sounds like all you need is something simple like:

hash.keys == array

The keys should come out in the same order as they are in the Hash so this is comparing the first key of the hash with the first element of the array, the second key with the second array element, ...

You could also transliterate what you're saying into Ruby like this:

hash.each_with_index.all? { |(k, _), i| k == array[i] }

Or you could say:

hash.zip(array).all? { |(k, _), e| k == e }

The zip version is pretty much the each_with_index version with the array indexing essentially folded into the zip.

Upvotes: 3

Related Questions