开发者

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


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>


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


I think you can do

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜