bonum_cete
bonum_cete

Reputation: 4962

search hash by value in ruby is returning nil

Im trying to search this hash by the value of :user

cache = {
  {:user=>1}=>{:last_visit=>2014-01-25 09:22:42 -0800, :frequency=>0},
  {:user=>2}=>{:last_visit=>2014-01-25 09:22:43 -0800, :frequency=>0},
  {:user=>3}=>{:last_visit=>2014-01-25 09:22:43 -0800, :frequency=>0}
}

I tried a number things including below but I always get nil

new_user = cache.select{|key, hash| hash[:user] == user }

new_user = cache.invert[:user=>user]

What am I doing wrong?

Upvotes: 0

Views: 74

Answers (1)

Arup Rakshit
Arup Rakshit

Reputation: 118271

Do as below

cache = {{:user=>1}=>{:last_visit=>'2014-01-25 09:22:42 -0800', :frequency=>0}, {:user=>2}=>{:last_visit=>'2014-01-25 09:22:43 -0800', :frequency=>0}, {:user=>3}=>{:last_visit=>'2014-01-25 09:22:43 -0800', :frequency=>0}}
cache.select{|key_hash,value_hsh| key_hash[:user] == 2 }
# => {{:user=>2}=>{:last_visit=>"2014-01-25 09:22:43 -0800", :frequency=>0}}

Your cache hash has keys and values, where keys are also hash and values are also hash. The symbol :user is a key of the key hash(s) of your cache hash. In your code cache.select{|key, hash| hash[:user] == user }, you were searching the key :user, in value hash, instead of a key hash.

Now as per the documentation Hash#[] -

Element Reference—Retrieves the value object corresponding to the key object. If not found, returns nil( if not default value is set, otherwise that default value).

So in your case hash[:user] always returned nil. Thus cache.select { .. } always returned empty array.

Upvotes: 5

Related Questions