-1

所以这是我正在使用的代码:

  @department_hash = {}
  department.css('li').each do | department |
    department_title = department.css('.refinementLink').text
    department_count = department.css('.narrowValue').text[/[\d,]+/]
    @department_hash[:department] ||= {}
    @department_hash[:department]["Pet Supplies"] ||= {}
    @department_hash[:department]["Pet Supplies"][department_title] = department_count
  end 

这会产生这样的东西:

{:department=>{"宠物用品"=>{""=>nil, "Birds"=>"15,863", "Cats"=>"243,396", "Dogs"=>"512,965", "Fish & Aquatic宠物"=>"46,428", "马"=>"14,738", "昆虫"=>"360", "爬行动物和两栖动物"=>"5,843", "小动物"=>"19,871"}}}

但我想要的是产生这样的东西:

{:department=>{"宠物用品"=>[""=>nil, "Birds"=>"15,863", "Cats"=>"243,396", "Dogs"=>"512,965", "Fish & Aquatic宠物"=>"46,428", "马"=>"14,738", "昆虫"=>"360", "爬行动物和两栖动物"=>"5,843", "小动物"=>"19,871"]}}

我该如何做到这一点?

编辑:

这个怎么样?这是有效的红宝石代码吗?

departments: { "Pet Supplies": [ "Birds" : 16651, "Cats" : 242910, etc ] }
4

1 回答 1

1

你不能。

你能做的最好的事情是这样的:

{ foo: [ { key: :value }, { key: :value } ] }

为此:

@department_hash = {}
  department.css('li').each do | department |
    department_title = department.css('.refinementLink').text
    department_count = department.css('.narrowValue').text[/[\d,]+/]
    @department_hash[:department] ||= {}
    @department_hash[:department]["Pet Supplies"] ||= []
    @department_hash[:department]["Pet Supplies"] << { key: :value } # replace with your own hash
  end 
end
于 2013-08-13T07:22:36.373 回答