本文介绍了如何更换一个数组的元素?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何能顶替一个数组中的元素?

  A = [1,2,3,4,5]

我需要用更换5 [11,22,33,44] .flatten!

A 现在变成了

  A = [1,2,3,4,11,22,33,44]


解决方案

不知道如果你正在寻找替代特定值或没有,但这个作品:

  A = [1,2,3,4,5]
B = [11,22,33,44]
一张地图! {| X |点¯x== 5?乙:X} .flatten!

该迭代的值 A ,并在找到 5 的值,它替换值与阵列 b ,然后变平阵列成一个阵列。

How can I substitue an element in an array?

a = [1,2,3,4,5]

I need to replace 5 with [11,22,33,44].flatten!

so that a now becomes

a = [1,2,3,4,11,22,33,44]
解决方案

Not sure if you're looking to substitute a particular value or not, but this works:

a = [1, 2, 3, 4, 5]
b = [11, 22, 33, 44]
a.map! { |x| x == 5 ? b : x }.flatten!

This iterates over the values of a, and when it finds a value of 5, it replaces that value with array b, then flattens the arrays into one array.

这篇关于如何更换一个数组的元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-13 07:03