开发者

Problem with multidimensional arrays in ruby [duplicate]

开发者 https://www.devze.com 2022-12-26 07:41 出处:网络
This question already has answers here: Value inside array having same object id [duplicate] (2 answers)
This question already has answers here: Value inside array having same object id [duplicate] (2 answers) Closed 9 months ago.

ruby 1.8.7 (2008-08-11 patchlevel 72) [i586-linux]

From script/console:

>> pairs = Array.new(2).map!{Array.new(2).map!{Array.new(2, Ar开发者_开发问答ray.new)}}
=> [[[[], []], [[], []]], [[[], []], [[], []]]]
>> pair = Pair.first
=> #<Pair id: 39, charge_card_id: 1, classroom_id: 1, timeslot_id: 1, created_at: "2010-04-01 00:45:37", updated_at: "2010-04-01 00:45:47">
>> pairs[0][0][0] << pair
=> [#<Pair id: 39, charge_card_id: 1, classroom_id: 1, timeslot_id: 1, created_at: "2010-04-01 00:45:37", updated_at: "2010-04-01 00:45:47">]
>> pairs[0][0]
=> [[#<Pair id: 39, charge_card_id: 1, classroom_id: 1, timeslot_id: 1, created_at: "2010-04-01 00:45:37", updated_at: "2010-04-01 00:45:47">], [#<Pair id: 39, charge_card_id: 1, classroom_id: 1, timeslot_id: 1, created_at: "2010-04-01 00:45:37", updated_at: "2010-04-01 00:45:47">]]
>>

So the question is why the pair object appears in pairs[0][0][0] AND in pairs[0][0][1] inspite of I did'n ask it to appear there. Notice I don't nedd to pairs[0][0][0] = pair - I want it as a first array member, so I need to use << or .push.


First of all, you want

pairs = Array.new(2) { Array.new(2) { Array.new(2) { [] }}}

instead of what you got. Two major differences:

  • you save yourself the #map! calls
  • in your example, "Array.new(2, Array.new)" is creating one Array which is used for both indices, so you are refering to the same array twice. By using the block syntax, you are ensuring that for every index you are having one separate instance of Array


Now works with:

pairs = Array.new(2).map!{Array.new(2).map!{Array.new(2).map!{Array.new}}}

I think it's because of the deepest arrays was just links to memory pointer.


Array.new(2, Array.new) gives you an array of size 2, with a copy of the same empty array object at both index 0 and index 1. If you want them to be different objects, use map! like you've done at the higher levels.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号