简体   繁体   English

迭代创建哈希哈希

[英]Iterate through to create a hash of hashes

As the final result I need a hash like: 作为最终结果,我需要一个哈希:

{items: {lorem: val1, dolor: val2}, {lorem: val1, dolor: val2}...}

eg a hash of hashes. 例如哈希哈希。

Put the problem is it should be created from iteration like this: 把问题放在它应该从迭代创建如下:

@result = []

@goods = {lorem: "ipsum", dolor: "sit"}

@items.each do |item|
  @goods.map do |k, v|
    if item.title == "ipsum"
      @result << [k, v]
    else
      @result << [k, item.title]
    end
  end
end

But this is not what I'm searching for, as @result is Array, and it's not 2-dimensional (as result i have [[foo, bar] [foo1,bar1]...]) 但这不是我正在寻找的,因为@result是数组,并且它不是二维的(因此我有[[foo,bar] [foo1,bar1] ...])

I see how k could be converted to Hash key (k.to_sym), but my problem is to have Hash of hashes as the final output. 我看到如何将k转换为Hash键(k.to_sym),但我的问题是将散列哈希值作为最终输出。

Ruby 1.9.3 (and Rails, but I believe this could be done without any Rails additions) Ruby 1.9.3(和Rails,但我相信这可以在没有任何Rails添加的情况下完成)

Many thanks. 非常感谢。

The format of the expected result is not a valid Hash. 预期结果的格式不是有效的哈希。

Instead of 代替

{items: {lorem: val1, dolor: val2}, {lorem: val1, dolor: val2}...}

It should be like this 它应该是这样的

{items: [{lorem: val1, dolor: val2}, {lorem: val1, dolor: val2}]}

It's also not hard to get the result you want 得到你想要的结果也不难

@items = []
@goods = {lorem: "ipsum", dolor: "sit"}
@items << @goods
@result = {items: @items}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM