Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/ruby/20.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在哈希ruby中向哈希添加值_Ruby - Fatal编程技术网

在哈希ruby中向哈希添加值

在哈希ruby中向哈希添加值,ruby,Ruby,我正在尝试做一个小实验,这让我现在很为难 我创建了新的散列 tt = Hash.new() 然后,我在其中添加两个带有键的哈希: tt.merge!(:in => Hash.new) tt.merge!(:out => Hash.new) 我有一个散列,看起来像这样: { :in => {}, :out => {} } tt = Hash.new(in: [], out: []) res.each do |x| if x[:id].nil?

我正在尝试做一个小实验,这让我现在很为难

我创建了新的散列

tt = Hash.new()
然后,我在其中添加两个带有键的哈希:

tt.merge!(:in => Hash.new)
tt.merge!(:out => Hash.new)
我有一个散列,看起来像这样:

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

res.each do  |x|
  if x[:id].nil?
    tt[:out] << x   
  else 
    tt[:in] << x
end
现在我有了另一个名为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 }}
}
另外-我应该为这个或数组使用哈希吗??我希望最终将其导出为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
tt=Hash.new(:in=>Hash.new,:out=>Hash.new)
合并!(:in=>Array.new)
合并!(:out=>Array.new)
ap tt类
res.each do|x|
如果x[:id]==nil

这是不可能的。你说的
{1,2,3,4,5}
是散列,但它不是散列,而是数组。如果没有与值关联的特定键,则没有类似散列的数据。使用数组的第二个版本是正确的(除了使用
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: {} }
完整且正确的版本可能如下所示:

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

res.each do  |x|
  if x[:id].nil?
    tt[:out] << x   
  else 
    tt[:in] << x
end
tt=Hash.new(输入:[],输出:[]
res.each do|x|
如果x[:id].nil?

tt[:out]谢谢!我已经更新了我的哈希示例,抱歉粘贴错误。它们不仅仅是1,2,3,4。你说
res
是散列,而是
res。每个
只包含一个参数。通常需要两个:键和值。你能举一个
res
的例子吗?