Michael Durrant
Michael Durrant

Reputation: 96604

Ruby -how can I gets the keys in a hash that have multiple values?

I have this hash:

@@MAPPINGS= {A: 2, B: 2, C: 2, D: 3, E: 3, F: 3, G: 4, H: 4, I: 4, J: 5, K: 5, L: 5, M: 6, N: 6, O: 6, P: 7, Q: 7, R: 7, S: 7, T: 8, U: 8, V: 8, W: 9, X: 9, Y: 9, Z: 9}

I want the key-value pairs that match a given value, e.g. for a value of 3 I want

{D: 3, E: 3, F: 3)

I tried:

@@MAPPINGS.keys[3]

and got

=> :D 

and

@@MAPPINGS[3].keys

but got

NoMethodError: undefined method `keys' for nil:NilClass

Upvotes: 0

Views: 67

Answers (1)

Michael Durrant
Michael Durrant

Reputation: 96604

Doing

@@MAPPINGS.select { |key,val| val == 3 }

was one option

Upvotes: 4

Related Questions