[英]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
? 我如何使用类似user.name
user[0].name
?
First of all, you don't need to initialise your Hashes before you use them - both calls to Hash.new
are unnecessary here. 首先,您不需要在使用哈希之前对其进行初始化-在这里不需要对Hash.new
两个调用。
Second, your only problem is that you're using the select
method. 其次,唯一的问题是您正在使用select
方法。 Quoting from the documentation : 引用文档 :
Returns a new hash consisting of entries for which the block returns true. 返回一个新的哈希值,该哈希值由该块返回true的条目组成。
That's not what you want. 那不是你想要的。 You want to use detect
: Passes each entry in enum to block. 您要使用detect
:将枚举中的每个条目传递给块。 Returns the first for which block is not false. 返回第一个不为false的块。
user = @user_hash.detect { |item| item["user_id"] == '001' }
user = @user_hash.detect { |item| item["user_id"] == '001' }
should work user = @user_hash.detect { |item| item["user_id"] == '001' }
应该可以
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
user = Hash.new
is a waste of time as you are overwriting it with the result of the following select
. user = Hash.new
是浪费时间,因为您使用以下select
结果覆盖它。
and select
returns an array of hashes that pass your test. 然后select
返回通过测试的哈希数组。
You want .find
or its synonym .detect
instead of .select
. 您需要.find
或其同义词.detect
而不是.select
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.