将值添加到哈希红宝石中的哈希值

时间:2012-11-22 20:46:38

标签: ruby

我正在尝试做一个让我难倒的小实验。

我创建了新的Hash

tt = Hash.new()

然后我用键添加两个哈希:

tt.merge!(:in => Hash.new)
tt.merge!(:out => Hash.new)

所以我有一个看起来像这样的哈希:

{
     :in => {},
    :out => {}
}

现在我有另一个名为res的散列哈希值,我遍历并对每个哈希值执行IF语句:

res.each do  |x|
    if x[:id] == nil
        tt[:out].merge!(x)
    else 
        tt[:in].merge!(x)
end 
end

但是,这只会将前一个哈希的最后一个值附加到新哈希中的out和in里面。

我要做的是使用IF语句将新哈希置于IN或OUT的键下

所以最终看起来像:

{
     :in => {{:1 => 1 ,:2 => 1 ,:3 => 1 ,:4 => 1 ,:5 => 1 },{:1 => 1 ,:2 => 1 ,:3 => 1 ,:4 => 1 ,:5 => 1 }},
    :out => {{:1 => 1 ,:2 => 1 ,:3 => 1 ,:4 => 1 ,:5 => 1 }, {:1 => 1 ,:2 => 1 ,:3 => 1 ,:4 => 1 ,:5 => 1 }}
}

另外 - 我应该使用Hashes这个还是阵列?我想最终将其导出为JSON。

例如,这有效。但不确定它是否正确:

tt = Hash.new(:in => Hash.new, :out => Hash.new)
tt.merge!(:in => Array.new)
tt.merge!(:out => Array.new)
ap tt.class
res.each do  |x|
    if x[:id] == nil
        tt[:out] << x   
    else 
        tt[:in] << x
end 
end

Thnaks

1 个答案:

答案 0 :(得分:0)

这是不可能的。你在谈论{1,2,3,4,5}作为哈希,但是不是哈希,它是一个数组。如果您没有与值关联的特定键,则表示您没有类似哈希的数据。你使用数组的第二个版本是正确的(除了你使用merge ...见下文)。

此外,如果您想在哈希中添加内容,则应使用[]运算符,而不是重复使用merge

例如,这是错误的:

tt = Hash.new()
tt.merge!(:in => Hash.new)
tt.merge!(:out => Hash.new)

你想要的是:

tt = Hash.new()
tt[:in] = Hash.new
tt[:out] = Hash.new

或更好,这个:

tt = { in: {}, out: {} }

完整正确的版本可能如下所示:

tt = Hash.new(in: [], out: [])

res.each do  |x|
  if x[:id].nil?
    tt[:out] << x   
  else 
    tt[:in] << x
end
相关问题