[Solved] How to compare this two hashes in ruby [closed]


1. Symbolize keys

These hashes are not equal because the keys are not equal. If you want to compare the values, no matter whether the keys are strings or symbols you can just transform the keys using to_sym. (Note that this will not transform nested keys).

first_hash.transform_keys(&:to_sym) == second_hash.transform_keys(&:to_sym)

2. Compare as JSON (NOT RECOMMENDED)

I do not recommend this, but since it is technically possible, I included it here for fun and informational purposes.

Another way you can do this is to check whether the JSON representation is the same. It is probably slower, and requires the keys to be in the same order in each hash.

require 'json'
first_hash.to_json == second_hash.to_json

8

solved How to compare this two hashes in ruby [closed]