⬆️ ⬇️

About jRuby and clone

As you know, in ruby ​​everything and everything is objects. This is a plus, but there are some difficulties in understanding the interaction with complex objects. Standard example:

person1 = "Tim"

person2 = person1

person1[0] = 'J'

person1 ->"Jim"

person2 -> "Jim"


There is a standard solution to this problem:



person1 = "Tim"

person2 = person1.clone

person1[0] = "J"

person1 -> "Jim"

person2 -> "Tim"


But let we have an object of the following form:

a= [[1,2,3],[4,5,6],[7,8,9]]

Apply the standard approach to it:

a = [[1,2,3],[4,5,6],[7,8,9]]

a1 = a.clone

a1[0] = [0,0,0]

puts a[0]

puts a1[0]


Let's complicate the task: it is required to build the array elements - 3, 6, 9 in a square. We will act by the standard method:

a = [[1,2,3],[4,5,6],[7,8,9]]

a1 = a.clone

a1.each{|item| item[2]=item[2]**2}

puts a[0]

puts a1[0]




My mistake in this case is that I do not take into account that everything in Ruby is an object and I work with links to the created objects.

In this case, I cloned the array itself a, but the subarrays of a1 remain references to the massives of a, respectively.

How I correct my mistake:

a = [[1,2,3],[4,5,6],[7,8,9]]

a1=[]

a.each { |item| a1[a.index(item)]=item.clone }

a1.each{|item| item[2]=item[2]**2}

puts a[0]

puts a1[0]




That is, it turns out that I have cloned each of the subarrays of object a, and therefore the entire array a is obtained.

Check it out:

a = [[1,2,3],[4,5,6],[7,8,9]]

a1=[]

a.each { |item| a1[a.index(item)]=item.clone }

a1[0]=[0,0,0]

puts a[0]

puts a1[0]




')

Source: https://habr.com/ru/post/39168/



All Articles