M.Octavio
M.Octavio

Reputation: 1808

how to use hash in ruby

I'm trying to use a hash to store the users. I have this code, and it's working, but it's not the way I want it:

@user_hash = Hash.new
@user_hash = User.all(:all)

user = Hash.new
user = @user_hash.select { |item| item["user_id"] == '001' }

puts user[0].name

How can I use something like user.name insted user[0].name ?

Upvotes: 0

Views: 166

Answers (3)

Tony Hopkinson
Tony Hopkinson

Reputation: 20330

user = Hash.new is a waste of time as you are overwriting it with the result of the following select.

and select returns an array of hashes that pass your test.

You want .find or its synonym .detect instead of .select.

Upvotes: 0

Nils Landt
Nils Landt

Reputation: 3134

First of all, you don't need to initialise your Hashes before you use them - both calls to Hash.new are unnecessary here.

Second, your only problem is that you're using the select method. Quoting from the documentation:

Returns a new hash consisting of entries for which the block returns true.

That's not what you want. You want to use detect: Passes each entry in enum to block. Returns the first for which block is not false.

user = @user_hash.detect { |item| item["user_id"] == '001' } should work

Upvotes: 5

Roland Mai
Roland Mai

Reputation: 31097

To create a hash you should use the following syntax:

@user_hash = Hash[User.find(:all).collect{|u| [u.user_id, u]}]

Then you can do something like:

puts user["001"].name

Upvotes: 1

Related Questions