簡體   English   中英

Ruby - 從哈希數組中提取特定鍵的值

[英]Ruby - Extract value of a particular key from array of hashes

我有一系列哈希 - @profiles,其數據如下:

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

我想得到full_name的說user_id = 7? 我正在做以下事情:但它正在拋出表達式@profiles.find{|h| h[':user_id'] == current_user.id}的錯誤 @profiles.find{|h| h[':user_id'] == current_user.id}為零。

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

如果我使用select而不是find那么錯誤是 - 沒有將String隱式轉換為Integer。

如何搜索哈希數組?

更新:

在@ 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

在視圖....,

p @current_job.full_names[current_user.id]

@profiles是一個散列數組,符號作為鍵,而你使用的是String對象。

所以':user_id'是一個字符串,你想要符號:user_id

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

我想得到full_name ,例如user_id == 7

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

注意,我使用Hash fetch for case,當key :user_id時沒有值為7哈希。

正如您所注意到的,提取user_id 7的名稱並不是很方便。您可以稍微修改一下您的數據結構:

@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

您沒有丟失任何信息,但名稱查找現在更快,更容易,更健壯。

建議,創建一個可以使事情更簡單的新哈希

例如:

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

profiles.each do |details|
  results[details[:user_id]] = details[:full_name]
end

現在,結果將有:

{5: "Emily Spot", 7: "Kevin Walls"}

因此,如果您需要獲取full_name,例如user_id = 7,只需執行以下操作:

results[7] # will give "Kevin Walls"

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM