组合来自两个单独数组的字符串元素

时间:2014-02-20 15:33:56

标签: ruby arrays

我有两个数组

names = ["name1", "name2"]
tracks = ["track1", "track2"]

我正在尝试将两个数组合并为一个新数组

data => ["name1 track1", "name2 track2"]

我尝试了以下

1)   @data = @name.zip(@tracks)flatten 
     produces ["name1", "track1", "name2", "track2"]

2)   @data = @name.at(0).concat(@tracks.at(0)) + @name.at(1).concat(@tracks.at(1))
     produces ["name1track1name2track2"]

3)   @name.each do |n|
      @tracks.each do |t|
       @data.push n + " " + t
       end
     end
     produces ["name1 track1", "name1 track2", "name2 track1", "name2 track2"]

我似乎无法解决这个问题。我将不胜感激。

8 个答案:

答案 0 :(得分:6)

names  = ["name1", "name2"] #note the "="
tracks = ["track1", "track2"]

p names.zip(tracks).map{|e| e.join(" ")}
#=> ["name1 track1", "name2 track2"]

答案 1 :(得分:1)

你可以这样做:

data = []
names.each_with_index {|x,y| data << "#{x} #{tracks[y]}" }
data # => ["name1 track1", "name2 track2"]

答案 2 :(得分:1)

names.map {|name| "#{name} #{tracks[names.index(name)]}"}
=> ["name1 track1", "name2 track2"]

答案 3 :(得分:0)

这是一个巧妙的方法:

names = ["name1", "name2"]
tracks = ["track1", "track2"]

names.zip(tracks).map { |a| a.join(" ") }
# => ["name1 track1", "name2 track2"]

首先,

names.zip(tracks)

给我们

[["name1", "track1"], ["name2", "track2"]]

然后我们使用map

将内部数组与空格连接起来

答案 4 :(得分:0)

我喜欢product方法

=> array_size = names.size
=> names.product(tracks).
     each_with_index.
     map { |x,i| x.join(" ") if (i % array_size - i / array_size).zero? }.compact
=> ["name1 track1", "name2 track2"]

答案 5 :(得分:0)

另:

names.map { |s| s << ' ' << tracks.shift }
  #=> ["name1 track1", "name2 track2"]

如果无法修改names(和/或tracks),则必须对副本进行操作。

变体:

[].tap { |a| names.size.times {a << (names.shift + ' ' + tracks.shift) } }

答案 6 :(得分:0)

有点不同的方式:

names  = ["name1", "name2"] 
tracks = ["track1", "track2"]

names.each_index.map { |i| "#{names[i]} #{tracks[i]}" }
# => ["name1 track1", "name2 track2"]

答案 7 :(得分:0)

另一种方式,与@ steenslag非常相似(我有时讨厌打开块:-))

names = ["name1", "name2", "name3"]
tracks = ["track1", "track2", "track3"]

names.zip([' '] * names.length, tracks).map(&:join)
=> ["name1 track1", "name2 track2", "name3 track3"]