删除1后输出为[2] [1,2],但输出为[2] [2]

时间:2014-09-15 23:10:53

标签: ruby-on-rails ruby ruby-on-rails-3 ruby-on-rails-4

删除1后输出为[2] [1,2]但输出为[2][2]

def array_dup(n,obj)

  array= []
  for i in 1..n
   print array.push(obj)[i]
 end

 return array
end

print (array_dup(5,'hi'))
c = array_dup(5, [1,2])
puts
print c

c[0].delete(1)
puts c
print c

puts

输出应如下所示:

["hi", "hi", "hi", "hi", "hi"]
[[2], [1, 2], [1, 2], [1, 2], [1, 2]]

但是,它看起来像:

["hi", "hi", "hi", "hi", "hi"]
[[1, 2], [1, 2], [1, 2], [1, 2], [1, 2]]2
2
2
2
2
[[2], [2], [2], [2], [2]]

1 个答案:

答案 0 :(得分:0)

试试这个解决方案,看起来似乎很大但是有效:

test_array = []
c.flatten[1..-1].each_slice(2).to_a.reverse_each {|x| test_array << x.reverse!}
puts test_array

<强>输出:

[[2], [1, 2], [1, 2], [1, 2], [1, 2]]