Why do you need to "replace" and not assign a new object to the same variable?

I looked at the Quiz resume in Solitaire Cipher when I came across this block of code:

def triple_cut
  a = @deck.index( 'A' )
  b = @deck.index( 'B' )
  a, b = b, a if a > b
  @deck.replace( [ @deck[(b + 1)..-1],
                   @deck[a..b],
                   @deck[0...a] ].flatten )
end

I do not understand why there is a separate method for this replace. Why not just do the following?

@deck = @deck[(b + 1)..-1] +
        @deck[a..b] +
        @deck[0...a]

Why use two different methods ( replaceand flatten) when you can just add them together? I have not encountered any problems.

+4
source share
3 answers

The beauty of a ruby ​​is that in many cases there is no right way to do something. In your case, I think your solution is as good as reading easier.

replace, , , .

x = [1, 2]
y = [3]
x.replace(y) # x is [3] and y is [3]
x << 5 # x is [3, 5] and y is [3]

x = [1, 2]
y = [3]
x = y # x is now pointing to the same object as y
x << 5 # both x and y are [3, 5] because they are the same object
+4
  • , .
  • .
+5

When replacing / redistributing large arrays, Array#replaceit seems better than assignment =.


require 'benchmark'

n = 500
ary_size = 10000

replacement = ['b']*ary_size*3

Benchmark.bm do |x|
  x.report { n.times { arr = ['a']*ary_size; arr.replace(replacement)} }
  x.report { n.times { arr = ['a']*ary_size; arr = replacement}}
end

Output:

       user     system      total        real
   0.000000   0.000000   0.000000 (  0.002253)
   0.015000   0.000000   0.015000 (  0.015224)
[Finished in 0.1s]
+4
source

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


All Articles