How to insert an array in the middle of an array?

I have an array of Ruby [1, 4]. I want to insert another array [2, 3]in the middle so that it becomes [1, 2, 3, 4]. I can achieve this with help [1, 4].insert(1, [2, 3]).flatten, but is there a better way to do this?

+4
source share
4 answers

You can do it as follows.

[1,4].insert(1,*[2,3])

The method insert()processes several parameters. Therefore, you can convert your array to parameters using the splat operator *.

+9
source

Array # [] = , index length. , rvalue , rvalue ( rvalue). :

b = [2,3]

a = [1,4]

1 (4), :

a[1,0] = b
  #=> [2,3]
a #=> [1,2,3,4]

:

a=[1,4]
a[0,0] = [2,3]
a #=> [2,3,1,4]

a=[1,4]
a[2,0] = [2,3]
a #=> [1,4,2,3]

a=[1,4]
a[4,0] = [2,3]
a #=> [1,4,nil,nil,2,3]]

.

+4
def insert_array receiver, pos, other
  receiver.insert pos, *other
end

insert_array [1, 4], 1, [2, 3]
#โ‡’ [1, 2, 3, 4]

, monkeypatching Array:

class Array
  def insert_array pos, other
    insert pos, *other
  end
end

, , . BTW, , , :

[1, [4,5]].insert 1, *[2,3]
#โ‡’ [1, 2, 3, [4,5]]

[1, [4,5]].insert(1, [2,3]).flatten
#โ‡’ [1, 2, 3, 4, 5]
+3

#

array = [1,2,3,6,7,8]
new_array = [4,5]

array[0...array.size/2] + new_array + array[array.size/2..-1]
0

Source: https://habr.com/ru/post/1626133/


All Articles