Mr. Black
Mr. Black

Reputation: 12082

Swap the array in single line

I know this is very silly question. But, I'm very eager to know how to swap the elements in a single line.

Ex:

a, b = 1, 2

I need the answer like this

a, b = 2, 1

Upvotes: 1

Views: 1476

Answers (3)

Larry K
Larry K

Reputation: 49104

a,b = b,a    # does work....

irb(main):017:0* a, b = 1, 2
=> [1, 2]
irb(main):018:0> a
=> 1
irb(main):019:0> b
=> 2
irb(main):020:0> a, b = b,a
=> [2, 1]
irb(main):021:0> a
=> 2
irb(main):022:0> b
=> 1
irb(main):023:0>

Upvotes: 5

Ed Swangren
Ed Swangren

Reputation: 124632

You say you want to swap an array in your title, yet not in your example. I'm going with the title, so...

x = [1,2,3,4,5]
x.reverse!
=> [5,4,3,2,1]

You could also do this... I guess...

a, b = 1, 2
a, b = b, a

Upvotes: 1

Reigo Hein
Reigo Hein

Reputation: 751

I think you can do

array[0, 1] = array[1, 0]

Upvotes: -2

Related Questions