抓取信息并以嵌套哈希中的键 => 值方式呈现它?



我有以下内容:

  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"=>["15,721", "243,247", "510,260", "46,007", "14,106", "358", "5,787", "19,808"]}

现在我想抢那些总数的标题

 department.css('.refinementLink').each do

它的输出是这样的:

{"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)]

您可以使用Array#zip组合两个数组:

numbers = ["15,721", "243,247"]
animals = ["Birds", "Cats"]
Hash[animals.zip(numbers)]
#=> {"Birds"=>"15,721", "Cats"=>"243,247"}

关于您的编辑:

既然您已经有了department_titledepartment_count,那么在您的循环中应该可以使用类似的东西:

@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

相关内容

  • 没有找到相关文章

最新更新