如何填充字符串数组以避免嵌套循环

时间:2017-05-06 08:17:13

标签: ruby-on-rails arrays ruby loops foreach

我必须根据三组不同的数组对象准备字符串数组

object1 = ['a', 'b', 'c']
object2 = [1, 2, 3, 4]
object3 = ['xx', 'yy']

目前,我正在使用嵌套循环

result = []
object1.each do |ob1|
  object2.each do |ob2|
    object3.each do |ob3|
      result << "#{ob1}-#{ob2}-#{ob3}"
    end
  end
end

result
=> ["a-1-xx", "a-1-yy", "a-2-xx", .... , "c-3-xx", "c-3-yy", "c-4-xx", "c-4-yy"]

是否有更好的方法以另一种方式填充数据以避免嵌套循环

2 个答案:

答案 0 :(得分:7)

你更喜欢这个吗?

object1.product(object2, object3).map { |e| e.join('-') }

答案 1 :(得分:2)

这是一种只用一个显式循环来定义数组的方法。没有使用隐藏的嵌套循环调用方法:

object1 = ['a', 'b', 'c']
object2 = [1, 2, 3, 4]
object3 = ['xx', 'yy']
n1, n2, n3 = object1.size, object2.size, object3.size

result = Array.new(n1 * n2 * n3) do |i|
  [
    object1[i / (n2 * n3)],
    object2[i / n3 % n2],
    object3[i % n3]
  ].join('-')
end
# ["a-1-xx", "a-1-yy", "a-2-xx", "a-2-yy", "a-3-xx", "a-3-yy", "a-4-xx", "a-4-yy", "b-1-xx", "b-1-yy", "b-2-xx", "b-2-yy", "b-3-xx", "b-3-yy", "b-4-xx", "b-4-yy", "c-1-xx", "c-1-yy", "c-2-xx", "c-2-yy", "c-3-xx", "c-3-yy", "c-4-xx", "c-4-yy"]
但是,它肯定不比你的代码更清晰或更强大。