[英]how to use hash in ruby
我正在尝试使用哈希来存储用户。 我有此代码,并且可以正常工作,但不是我想要的方式:
@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
我如何使用类似user.name
user[0].name
?
首先,您不需要在使用哈希之前对其进行初始化-在这里不需要对Hash.new
两个调用。
其次,唯一的问题是您正在使用select
方法。 引用文档 :
返回一个新的哈希值,该哈希值由该块返回true的条目组成。
那不是你想要的。 您要使用detect
:将枚举中的每个条目传递给块。 返回第一个不为false的块。
user = @user_hash.detect { |item| item["user_id"] == '001' }
user = @user_hash.detect { |item| item["user_id"] == '001' }
应该可以
要创建哈希,您应该使用以下语法:
@user_hash = Hash[User.find(:all).collect{|u| [u.user_id, u]}]
然后,您可以执行以下操作:
puts user["001"].name
user = Hash.new
是浪费时间,因为您使用以下select
结果覆盖它。
然后select
返回通过测试的哈希数组。
您需要.find
或其同义词.detect
而不是.select
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.