خرید بک لینک

Vote count: -1

I have an array filled with default strings, and I'm trying to replace part of the characters in the default string at random position.

If I do something like this, I will have all elements in the array changed:

arr = ["*"] * 10
arr[0][0..2] = "aaa"
arr 
# => ["aaa", "aaa", "aaa", "aaa", "aaa", "aaa", "aaa", "aaa", "aaa", "aaa"]

But if I initialize an array in a different way, it works:

(0..10).each.map {|i| arr[i] = "*"}
arr[0][0..2] = "aaa"
arr
# => ["aaa", "*", "*", "*", "*", "*", "*", "*", "*", "*", "*"]

What is the background for such behavior?

asked 10 mins ago

2 Answers

Vote count: 1

Arrays store references to objects, when you initialize array that way - you get an array with 10 references to the same string. Then you modify the string.

arr = ['*']*3
# => ["*", "*", "*"]
arr.map &:object_id
# => [70305424624600, 70305424624600, 70305424624600]

answered 4 mins ago

Vote count: 0

The reason is illustrated with the following code:

irb(main):021:0> (0..10).each.map { |i| arr[i] = "*" }
=> ["*", "*", "*", "*", "*", "*", "*", "*", "*", "*", "*"]
irb(main):022:0> arr[0].equal? arr[1]
=> false # first object is NOT equal to second object (different objects)
irb(main):023:0> arr=["*"]*10
=> ["*", "*", "*", "*", "*", "*", "*", "*", "*", "*"]
irb(main):024:0> arr[0].equal? arr[1]
=> true # first object IS equal to second object (same object)

Basically, when you do arr=["*"]*10 you're literally putting the exact same String object into all array slots. Whereas, (0..10).each.map { |i| arr[i] = "*" } is creating a new String object for each element in the array.

answered 4 mins ago

برچسب: نویسنده: استخدام کار تاريخ: جمعه 13 فروردين 1395 ساعت: 0:22

صفحه بندی