合并在一个阵列中的红宝石两个数组的只有各元素 [英] Merging only respective elements of two arrays in one array in ruby
本文介绍了合并在一个阵列中的红宝石两个数组的只有各元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
您好我有红宝石以下两个数组
Hello I have the following two arrays in ruby
A=["a","b","c"]
B=["d","e","f"]
和我想生产这种
C = ["ad", "be", "cf"]
无论数组的长度。两个数组都是一样的长度,但。
regardless of array length. The two arrays are always the same length though.
有一个整洁的方式做到这一点?我的意思,而不是通过阵列,一个迭代循环。
Is there a neat way to do this? I mean instead of iterating through the arrays with a for loop.
推荐答案
Very simple with the method Array#zip
and Array#map
:
A = ["a","b","c"]
B = ["d","e","f"]
A.zip(B).map { |a| a.join }
# => ["ad", "be", "cf"]
# or
A.zip(B).map(&:join)
# => ["ad", "be", "cf"]
另一种方式(但不是很好看): - )
One more way ( but not looks good ), :-)
A.map.with_index { |e,i| e + B[i] }
# => ["ad", "be", "cf"]
这篇关于合并在一个阵列中的红宝石两个数组的只有各元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文