ruby中的数组更新

时间:2015-04-29 10:10:14

标签: ruby

给出两个数组:

s1 = ["Arun#2#very good shop","Mani#4#i am very glad to meet you sir.","Anu#2#not bad"]
s2 = ["first","second","third"]

我想要一个新的数组s3,如:

s3 = ["Arun#2#very good shop#first","Mani#4#i am very glad to meet you sir#second.","Anu#2#not bad#third"]

3 个答案:

答案 0 :(得分:8)

s3 = s1.zip(s2).map{ |x| x.join('#')}
=> ["Arun#2#very good shop#first", "Mani#4#i am very glad to meet you sir.#second", "Anu#2#not bad#third"]

答案 1 :(得分:2)

试试这个:

> s3 = [s1,s2].transpose.map{|a| a.join("#")}
 => ["Arun#2#very good shop#first", "Mani#4#i am very glad to meet you sir.#second", "Anu#2#not bad#third"]

注意:如果两个数组具有相同数量的元素,这将有效。

替代选项:这适用于两个数组中的任意数量的元素

> s1.zip(["#"].cycle, s2).map(&:join)
 => ["Arun#2#very good shop#first", "Mani#4#i am very glad to meet you sir.#second", "Anu#2#not bad#third"]

答案 2 :(得分:0)

假设您想在s2后的相应索引处追加s1#的元素:

s3 = []
s1.each_with_index{|a, i| s3 << a + "#" + s2[i].to_s}
s3
# => ["Arun#2#very good shop#first", "Mani#4#i am very glad to meet you sir.#second", "Anu#2#not bad#third"]