刮取信息并在密钥中显示=>在嵌套哈希中重视时尚?

时间:2013-08-12 06:36:30

标签: 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 

输出如下内容:

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

1 个答案:

答案 0 :(得分:1)

您可以使用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