Fabio Andres
Fabio Andres

Reputation: 57

Is there a way to check if a hash value in Ruby is the same throughout or compare only the values for equality?

I have the below code that returns the number of instances of an item in an array as a hash. I now need to check if the value is the same. For example if the hash is like this = {1=>3, 2=>3} i need to check if the value is the same, in this case it is but dont know how to check this.

arr.inject(Hash.new(0)) {|number,index| number[index] += 1 ;number}

Thanks

Upvotes: 1

Views: 48

Answers (1)

Ursus
Ursus

Reputation: 30056

So, given h = { 1 => 3, 2 => 3 }, if I got you, you want to know if the values are ALL the same. If you knew the keys you could do

all_the_same = h[1] == h[2]

If there are more keys you want to check

all_the_same = h.values_at(1, 2, 3, 4).uniq.length == 1

If you don't know how many keys you have or which are these keys you could do

all_the_same = h.values.uniq.length == 1

Upvotes: 1

Related Questions