繁体   English   中英

如何在Ruby中使用哈希

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM