如何将元素插入到数组中

时间:2014-07-14 07:15:33

标签: ruby arrays

我有一个由未知元素组成的数组:

myary = [100, "hello", 20, 40, "hi"]

我想在每个元素之后放置整数10以使其成为:

myary = [100, 10, "hello", 10, 20, 10, 40, 10, "hi", 10]

有办法或方法吗?

另一个问题是我需要在字符串10之前添加整数"hello"

myary = [100, 10,"hello", 20, 40, "hi"]

1 个答案:

答案 0 :(得分:9)

这是你想要的吗?

myary = [100, "hello", 20, 40, "hi"]
myary.flat_map { |i| [i, 10] }
# => [100, 10, "hello", 10, 20, 10, 40, 10, "hi", 10] 
myary.flat_map { |i| i == 'hello' ? [10, i] : i }
# => [100, 10,"hello", 20, 40, "hi"]

阅读#flat_map方法。