How to splice array and merge back in Ruby?

Does

New Member
#1
Say I have 2D array like so:
Mã:
[ 3,    4,   8,   12 ]
[ 2,    6,   7,   16 ]
[ 1,   10,  11,   15 ]
[ 5,    9,  13,   14 ]
I want to shift 6 in [1][1] and unshift it into [2][1]

So that I can get the following:
Mã:
[ 3,    4,   8,    12 ]
[ 2,    7,   11,   16 ]
[ 1,    6,   10,   15 ]
[ 5,    9,   13,   14 ]
I thought I'd splice(1,1) 2nd and 3rd array to get:
Mã:
a: [6, 7]
b: [10, 11]
and then do:
Mã:
b.unshift(a.shift)
a << b.pop
 

Admin

Administrator
Thành viên BQT
#2
Given this array:
Mã:
ary = [
        [ 3,    4,   8,   12 ],
        [ 2,    6,   7,   16 ],
        [ 1,   10,  11,   15 ],
        [ 5,    9,  13,   14 ]
      ]
You can do it by parallel assignment:
Mã:
ary[2][1], ary[1][1], ary[2][2], ary[1][2] = ary[1][1], ary[1][2], ary[2][1], ary[2][2]
Maybe you can turn it into a method.
 

Từ khóa phổ biến

You are using an out of date browser. It may not display this or other websites correctly.
You should upgrade or use an alternative browser.

Top