Richlewis Richlewis - 10 months ago 48
Ruby Question

comparing a hashes value against array in order

If I have the following hash and array

hash = {'i' => 'i', 'av' => 'av', 'deviceName' => 'Genymotionvbox86p'}
array = ['i', 'av', 'Genymotionvbox86p']

How could I compare that each item in the array matches the hashes value in the same order

So far I have

array.each do |value|
hash.each do |k, v|
expect(v).to eq(value), "expected #{k} to equal #{v}, instead got #{value}"

This is failing as I get

expected av to equal av, instead got i (RSpec::Expectations::ExpectationNotMetError)

Im not quite there yet and imagine that a loop within a loop is not the best thing to do either?

Any help appreciated as would like to know how to efficiently approach this



If you would really want to compare item-by-item, you rightfully noticed that a loop within a loop is not the way to go. You need a single loop to iterate both structures.

For that, you can, for example, use zip, to combine hash and array: do |(hash_key, hash_value), array_item|
  expect(hash_value).to eq array_item

or you can resort to using an index:

hash.each_with_index do |(k, v), i|
  expect(v).to eq array[i]