7, :full_name=>"Kevin-6ren">
gpt4 book ai didi

ruby-on-rails - Ruby - 从哈希数组中提取特定键的值

转载 作者:数据小太阳 更新时间:2023-10-29 07:23:33 25 4
gpt4 key购买 nike

我有一个散列数组 - @profiles 的数据为:

[{:user_id=>5, :full_name=>"Emily Spot"},{:user_id=>7, :full_name=>"Kevin Walls"}]

我想获得 user_id = 7 的全名?我正在执行以下操作:但是表达式 @profiles.find{|h| 抛出错误h[':user_id'] == current_user.id} 为 nil。

name = @profiles.find{ |h| h[':user_id'] == current_user.id }[':full_name']

如果我使用 select 而不是 find 那么错误是 - 没有将 String 隐式转换为 Integer。

如何搜索哈希数组?

更新:

在@Eric 的回答之后,我重新构建了我的工作模型和 View 操作:

  def full_names
profile_arr||= []
profile_arr = self.applications.pluck(:user_id)
@profiles = Profile.where(:user_id => profile_arr).select([:user_id, :first_name, :last_name]).map {|e| {user_id: e.user_id, full_name: e.full_name} }
@full_names = @profiles.each_with_object({}) do |profile, names|
names[profile[:user_id]] = profile[:full_name]
end
end

在 View ....,

p @current_job.full_names[current_user.id]

最佳答案

@profiles 是一个散列数组,以符号作为键,而您使用的是 String 对象。

所以 ':user_id' 是一个字符串,你想要符号::user_id:

@profiles.find{ |h| h[:user_id] == current_user.id } 

I want to get full_name of say user_id == 7

@profiles.find { |hash| hash[:user_id] == 7 }.fetch(:full_name, nil)

请注意,我使用了 Hash#fetch例如,当键 :user_id 处没有值为 7 的散列时。

关于ruby-on-rails - Ruby - 从哈希数组中提取特定键的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43182848/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com