Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why would you `replace` rather than assign a new object to the same variable?

I was looking over the Quiz Summary in Solitaire Cipher, when I stumbled upon 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 don't understand why there's a separate method replace for this. Why not just do the following?

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

Why go through the trouble of applying two separate methods (replace and flatten) when you could just add them together? I didn't run into any problems with it.

like image 618
Ryan Lue Avatar asked Dec 11 '22 18:12

Ryan Lue


1 Answers

  1. It saves memory by not re-creating the array.
  2. You can refer to the same object without re-assigning the variable.
like image 58
sawa Avatar answered May 21 '23 08:05

sawa