Ruby on rails Ruby构建哈希数组中的哈希

Ruby on rails Ruby构建哈希数组中的哈希,ruby-on-rails,arrays,ruby,hash,Ruby On Rails,Arrays,Ruby,Hash,我有特殊的数组和散列结构,如下所示 [ { Qid: '3', QName: 'Test1', filled_out: [ { Id: '234', Date: '25.04.2015 23:14:15', Score: rand(10..100)}, { Id: '4587', Date: '27.04.2015 11:13:15', Score: rand(10..100)}, { Id: '33254', Date: '23.05.2015 09:

我有特殊的数组和散列结构,如下所示

[
  { Qid: '3', QName: 'Test1', filled_out: [
      { Id: '234', Date: '25.04.2015 23:14:15', Score: rand(10..100)},
      { Id: '4587',  Date: '27.04.2015 11:13:15', Score: rand(10..100)},
      { Id: '33254', Date: '23.05.2015 09:19:17', Score: rand(10..100)}
    ]
  },
  {
    Qid: '3', QName: 'Test2', filled_out: [
      { Id: '2478', Date: '25.04.2015 23:14:15', Score: rand(10..100) },
      { Id: '12357', Date: '27.04.2015 11:13:15', Score: rand(10..100) },
      { Id: '9654', Date: '23.05.2015 09:19:17', Score: rand(10..100) }
    ]
  },
  {
    Qid: '3', QName: 'Test3', filled_out: [
      { Id: '47854', Date: '25.04.2015 23:14:15', Score: rand(10..100) },
      { Id: '12365', Date: '27.04.2015 11:13:15', Score: rand(10..100) },
      { Id: '77788547', Date: '23.05.2015 09:19:17', Score: rand(10..100) }
    ]
  },
  {
    Qid: '3', QName: 'Test4', filled_out: [
      { Id: '1214', Date: '25.04.2015 23:14:15', Score: rand(10..100) },
      { Id: '5698', Date: '27.04.2015 11:13:15', Score: rand(10..100)},
      { Id: '1906', Date: '23.05.2015 09:19:17', Score: rand(10..100) }
    ]
  }
]
根据代码,此构造是静态的。现在我想尝试用随机发生器创建这个结构

我试过这个代码,但不起作用

@arr = Array.new

rand(1..12).times do |i|
    @v = Hash.new
    @v[:Qid] = rand(10..1000)
    @v[:QName] = 'Test'
    @v[:filled_out] = nil

    rand(1..8).times do |k|
      @q = Hash.new
      @q[:Id] = rand(10..1000)
      @q[:Date] = '25.04.2015 23:14:15'
      @q[:Score] = rand(1..100)

      @v[:filled_out] << @q
    end
  @arr << @v
end
@arr=Array.new
兰特(1..12)。时间是我的|
@v=Hash.new
@v[:Qid]=兰特(10..1000)
@v[:QName]=“测试”
@v[:填写]=无
兰德(1..8)。泰晤士报|
@q=散列。新
@q[:Id]=兰特(10..1000)
@q[:日期]=“25.04.2015 23:14:15”
@q[:分数]=兰特(1..100)

@v[:filled_out]替换
我的建议是先构建数组,然后迭代它们

下面是我总结的一个例子:

arr = Array.new(rand(1..12))

arr.each_with_index do |v, i|
  filled_out = Array.new(rand(1..8))

  filled_out.each_with_index do |j, k|
    filled_out[k] = {
      'Id': rand(10..1000),
      'Date': '25.04.2015 23:14:15',
      'Score': rand(1..100)
    }
  end

  arr[i] = {
    'Qid': rand(10..1000),
    'QName': "test",
    'filled_out': filled_out
  }

end

puts arr
您可能会删除
每个带有_索引的_
,并添加其他内容,以避免使用未编入索引的变量,但我只是将其放在一起,向您展示一个工作示例


有时,当您构建这样的数据时,最好使用相对于最终结果更详细的代码。

我看到两个
do
s和一个
end
。我认为
rand(1.8)
中有一个输入错误,我没有看到每个
方法。最后一行之后存在“end”(arr我将rand(1.8)固定为rand(1..8).Now Ruby说:undefined method`Now Ruby说:没有将符号隐式转换为整数,但看起来哈希将覆盖每个循环,而不是附加,不是吗?它在哪一行给出错误?看这里,我工作时没有任何错误: