Ruby 抓取信息并将其显示在密钥中=>;嵌套哈希中的值样式?

Ruby 抓取信息并将其显示在密钥中=>;嵌套哈希中的值样式?,ruby,nokogiri,Ruby,Nokogiri,我有以下资料: department = data.css('#ref_2619534011') @department_hash = Hash.new {|h,k| h[k]=[]} department.css('.narrowValue').each do | department | @department_hash["department"] << department.text end 现在我想抓住这些总数的标题 dep

我有以下资料:

  department = data.css('#ref_2619534011')

  @department_hash = Hash.new {|h,k| h[k]=[]}
  department.css('.narrowValue').each do | department |
    @department_hash["department"] << department.text
  end 
现在我想抓住这些总数的标题

 department.css('.refinementLink').each do
其输出如下:

{"department"=>["15,721", "243,247", "510,260", "46,007", "14,106", "358", "5,787", "19,808"]}
{"department"=>["Bird", "Cats", etc ]}
{departments: { "Pet Supplies": [ "Birds" : 15,721, "Cats" : 243,247, etc ] }}
我想混合这两种方法来生成一个嵌套哈希,如下所示:

{"department"=>["15,721", "243,247", "510,260", "46,007", "14,106", "358", "5,787", "19,808"]}
{"department"=>["Bird", "Cats", etc ]}
{departments: { "Pet Supplies": [ "Birds" : 15,721, "Cats" : 243,247, etc ] }}
如何做到这一点

编辑:

我试过了,但没有成功:

 @department_hash = Hash.new {|h,k| h[k]=[]}
  department.css('li').each do | department |
    department_title = department.css('.refinementLink').text
    department_count = department.css('.narrowValue').text[/[\d,]+/]
  end 

  @department_hash["department"] = Hash[department_title.zip(department_count)]
您可以使用组合两个阵列:

numbers = ["15,721", "243,247"]
animals = ["Birds", "Cats"]

Hash[animals.zip(numbers)]
#=> {"Birds"=>"15,721", "Cats"=>"243,247"}
关于您的编辑:

由于您已经准备好了
部门标题
部门计数
,在您的循环中类似的内容应该可以工作:

@department_hash = {}
department.css('li').each do |department|
  department_title = ...
  department_count = ...
  @department_hash["department"] ||= {}   # ensure empty hash
  @department_hash["department"][department_title] = department_count
end

我试着将它合并到我的代码中,但没有成功。请看我的EDIT@alexchenco
department\u title
department\u count
在您的循环之外不可用。我已经更新了我的答案。非常感谢!顺便问一下,我如何添加“宠物用品”部分(只是作为嵌套哈希的标题?)我认为
@department\u hash[“department”][“Pet Supplies”]=…
是您要寻找的语法。