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

Mea*_*ans 4 ruby arrays hash ruby-on-rails

我有一系列哈希 - @profiles,其数据如下:

[{:user_id=>5, :full_name=>"Emily Spot"},{:user_id=>7, :full_name=>"Kevin Walls"}]
Run Code Online (Sandbox Code Playgroud)

我想得到full_name的说user_id = 7?我正在做以下事情:但它抛出一个表达式@profiles.find{|h| h[':user_id'] == current_user.id}为零的错误.

name = @profiles.find{ |h| h[':user_id'] == current_user.id }[':full_name']
Run Code Online (Sandbox Code Playgroud)

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

如何搜索哈希数组?

更新:

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

  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
Run Code Online (Sandbox Code Playgroud)

在视图....,

p @current_job.full_names[current_user.id]
Run Code Online (Sandbox Code Playgroud)

And*_*eko 6

@profiles是一个哈希数组,符号作为键,而你使用的是String对象.

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

@profiles.find{ |h| h[:user_id] == current_user.id } 
Run Code Online (Sandbox Code Playgroud)

full_name想说user_id == 7

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

注意,我使用Hash#fetch for case,当7key 没有值为hash 时:user_id.


Eri*_*nil 4

正如您所注意到的,提取 7 的名称并不是很方便。user_id您可以稍微修改一下数据结构:

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

@full_names = @profiles.each_with_object({}) do |profile, names|
  names[profile[:user_id]] = profile[:full_name]
end

p @full_names
# {5=>"Emily Spot", 7=>"Kevin Walls"}
p @full_names[7]
# "Kevin Walls"
p @full_names[6]
# nil
Run Code Online (Sandbox Code Playgroud)

您没有丢失任何信息,但姓名查找现在更快、更容易、更强大。