In Ruby, how to replace an element in an array with potentially multiple elements?

Using Ruby 2.4. I have an array of strings. How to replace one element in an array with potentially multiple elements? I have

phrases[index] = tokens 

However, tokens is an array, and right now this is creating an array of phrases with strings and an array ...

["abc", ["a", "b"], "123"]

If the tokens are ["a", "b"], and index is 1, I would like the result to be

["abc", "a", "b", "123"]

How to do it?

+4
source share
3 answers

You can specify startand lengthwith Array#[]=; replaces index submatrix startfor lengthelements

or indicate range; replaces the submatrix specified by the index range.

phrases = ["abc", "token_placeholder", "123"]
tokens = ["a", "b"]
index = 1
phrases[index, 1] = tokens
#       ^^^^^^^^^ ------------------ start and length

# OR phrases[index..index] = tokens
#            ^^^^^^^^^^^^ -------------- range

phrases # => ["abc", "a", "b", "123"]
+4

Enumerable # flat_map:

arr = ["abc", ["a", "b"], "123"]

arr.flat_map(&:itself)
  #=> ["abc", "a", "b", "123"] 

arr . arr ,

arr.replace(arr.flat_map(&:itself))
  #=> ["abc", "a", "b", "123"] 
arr
  #=> ["abc", "a", "b", "123"] 
0

A flat map would be the best way to do this, it displays (converts), then aligns the list to a single array. Let's say we wanted to add two elements for even numbers:

(1..10).flat_map { |i| i.even? ? [i, i**2] : i }

He will return:

[1, 2, 4, 3, 4, 16, 5, 6, 36, 7, 8, 64, 9, 10, 100]

Compared to the returned card:

[1, [2, 4], 3, [4, 16], 5, [6, 36], 7, [8, 64], 9, [10, 100]]
0
source

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


All Articles