-1

我有以下内容:

  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)]
4

1 回答 1

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
于 2013-08-12T07:39:45.950 回答