owade
owade

Reputation: 306

Swap arrays in Ruby

I have created a method that inherits from Array class to swap two arrays:

class Array
  def exchange_with!(other_array)
    self,other_array=other_array,self
  end
end

But i get error Can't change the value of self (SyntaxError). I have also tried:

class Array
  def exchange_with!(other_array)
    self.replace(other_array)
    other_array.replace(self)
  end
end

But it returns value of last swaped array:

a=[1,2,4]
b=[5,6,7]
a.exchange_with!(b)
a #> [5, 6, 7]
b #> [5, 6, 7]

what i need is a #> [5, 6, 7] and b #>[1, 2, 4]

Upvotes: 0

Views: 688

Answers (1)

Wand Maker
Wand Maker

Reputation: 18762

Try below:

class Array
  def exchange_with!(other_array)
    other = self.dup
    self.replace(other_array)
    other_array.replace(other)
  end
end

You cannot assign new values to self, but you can always modify the contents of self by using methods available on that class.

Here we can use Array#replace to replace the contents of an array with another ary.

To better understand, how variables are passed to methods in Ruby, have a look at this article.

Upvotes: 2

Related Questions