如何将类似于此{{}}的哈希转换为类似于此{{[]}}的哈希

  • 本文关键字:哈希 类似于 转换 ruby hash nokogiri
  • 更新时间 :
  • 英文 :


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

  @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=>{"宠物用品"=>{"=>零,"Birds"=>"15863","猫"=>"243396","狗"=>"512965",《鱼类和水生宠物》=>"46428","马"=>"14738","昆虫"=>"360","爬行动物&两栖动物"=>"5843","小动物"=>"19871"}}

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

{:部门=>{"宠物用品"=>["=>零,"鸟类"=>"15863","猫"=>"243396","狗"=>"512965",《鱼类和水生宠物》=>"46428","马"=>"14738","昆虫"=>"360","爬行动物&两栖动物"=>"5843","小动物"=>"19871"]}}

我该如何做到这一点?

编辑:

这个怎么样?这是有效的ruby代码吗?

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

你不能。

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

{ 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

相关内容

  • 没有找到相关文章

最新更新