1
我是新來的紅寶石,所以我顯然誤解了一些東西。我意欲創建大小2,其中每個元件本身是一個陣列,然後推項的一個或另一個子陣列的陣列:二維數組,推送到一個數組顯示在所有數組?
#!/usr/bin/env ruby
arr = Array.new(2, Array.new)
puts 'default, no entries:'
arr.each_with_index { |a, i| puts 'arr[' + i.to_s + '] = ' + a.to_s }
puts ''
puts 'adding "kitty" to arr[0]:'
arr[0].push('kitty') # add an element to the sub-array at arr[0]
arr.each_with_index { |a, i| puts 'arr[' + i.to_s + '] = ' + a.to_s }
puts ''
puts 'adding "doggy" to arr[1]:'
arr[1].push('doggy') # add an element to the sub-array at arr[1]
arr.each_with_index { |a, i| puts 'arr[' + i.to_s + '] = ' + a.to_s }
輸出:
default, no entries:
arr[0] = []
arr[1] = []
adding "kitty" to arr[0]:
arr[0] = ["kitty"]
arr[1] = ["kitty"]
adding "doggy" to arr[1]:
arr[0] = ["kitty", "doggy"]
arr[1] = ["kitty", "doggy"]
我期望ARR [0] .push()在arr [0] [0]處添加元素,那是錯誤的嗎?
啊哈!現在有道理,謝謝! – jgor
你可以用'arr.map(&:object_id)#=> [70190130252680,70190130252680] –