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 ?
First of all, you don’t need to initialise your Hashes before you use them – both calls to
Hash.neware unnecessary here.Second, your only problem is that you’re using the
selectmethod. Quoting from the documentation: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