创建一个包含其他两个数组的信息的数组

时间:2012-10-02 21:20:29

标签: ruby arrays

如何使用以下两个数组来创建数组:

name = [a,b,c]

how_many_of_each [3,5,2]

获取

my_array = [a,a,a,b,b,b,b,b,c,c]

5 个答案:

答案 0 :(得分:11)

使用zipflat_map和数组乘法:

irb(main):001:0> value = [:a, :b, :c]
=> [:a, :b, :c]
irb(main):002:0> times = [3, 5, 2]
=> [3, 5, 2]
irb(main):003:0> value.zip(times).flat_map { |v, t| [v] * t }
=> [:a, :a, :a, :b, :b, :b, :b, :b, :c, :c]

答案 1 :(得分:3)

name.zip(how_many_of_each).inject([]) do |memo, (x, y)|
  y.times { memo << x}
  memo
end

=> [:a, :a, :a, :b, :b, :b, :b, :b, :c, :c]
编辑:哦,好,请看@David Grayson。

答案 2 :(得分:2)

这将以易于理解的方式进行:

my_array = []
name.count.times do |i|
    how_many_of_each[i].times { my_array << name[i] }
end

答案 3 :(得分:1)

array = ["a", "b", "c"]
how_many = [2, 2, 2]

result = []

array.each_with_index do |item, index|
  how_many[index].times { result << item }
end

print result # => ["a", "a", "b", "b", "c", "c"]

答案 4 :(得分:1)

你可以选择你想要的那个(只需交换评论#):

class Array
    def multiply_times(how_many)
        r = []
        #how_many.length.times { |i| how_many[i].times { r << self[i] } }
        self.each_with_index { |e, i| how_many[i].times { r << e } }
        r
    end
end

p ['a', 'b', 'c'].multiply_times([3, 5, 2])
#=> ["a", "a", "a", "b", "b", "b", "b", "b", "c", "c"]