Hash哈希数组哈希,Itunes wishlist

时间:2012-11-18 09:31:20

标签: ruby-on-rails ruby cookies hash

干杯!请帮我解决问题 - 我有一个cookie,哈希:

> cookies.keys
=> [:wishlist]

然后:

> cookies[:wishlist].keys
=> ["result_count", "results"]

结果是一个Hashie :: rash

的数组
> cookies[:wishlist].results[0].keys
=> ["wrapper_type", "kind", "artist_id", ...]

cookies是哈希,cookies [:wishlist]是Hashie :: Rash,结果是一个数组,其中包含其他Hashie :: Rash'ies。 问题是如何在不删除旧数据的情况下将新数据添加到wishlist(例如,将轨道添加到心愿单)?

1 个答案:

答案 0 :(得分:2)

假设你有这个结构:

cookies = {
  :wishlist => Hashie::Rash.new({
    'resultCount' => 2,
    'results' => [
      Hashie::Rash.new({
        'wrapperType' => 'foo1',
        'kind'        => 'bar1',
        'artistId'    => 'baz1'
      }),
      Hashie::Rash.new({
        'wrapperType' => 'foo2',
        'kind'        => 'bar2',
        'artistId'    => 'baz2'
      })
    ]
  })
}

您只需使用Array#pushresults添加新项目:

require 'rash'

new_wishlist_item = Hashie::Rash.new({
  'wrapperType' => 'foo3',
  'kind'        => 'bar3',
  'artistId'    => 'baz3'
})

cookies[:wishlist].results.push( new_wishlist_item )
cookies[:wishlist].result_count = results.count

cookies[:wishlist].results.each do |r|
  puts r.wrapper_type
end

输出:

foo1
foo2
foo3