Ruby on rails 空值置换的Ruby方法/算法

Ruby on rails 空值置换的Ruby方法/算法,ruby-on-rails,ruby,algorithm,Ruby On Rails,Ruby,Algorithm,我有3个列表:标题、子标题和图像URL 每个列表都是一个数组,每个列表可能包含0个或更多项 我想以这种格式创建每个组合的排列: [ {headline: X1, subheadline: Y1, image_url: Z1} {headline: X1, subheadline: Y2, image_url: Z1} {headline: X1, subheadline: Y3, image_url: Z1} {headline: X1, subheadline: Y1, ima

我有3个列表:标题、子标题和图像URL

每个列表都是一个数组,每个列表可能包含0个或更多项

我想以这种格式创建每个组合的排列:

[
  {headline: X1, subheadline: Y1, image_url: Z1}
  {headline: X1, subheadline: Y2, image_url: Z1}
  {headline: X1, subheadline: Y3, image_url: Z1}
  {headline: X1, subheadline: Y1, image_url: Z2} 
  ...
]
唯一的问题是,对于任何缺少的项目,我希望它是一个空字符串
'

我第一次遇到的“愚蠢”解决方案是

headlines.each do |headline|
  subheadlines.each do |subheadline|
    image_urls.each do |url|
      {headline: headline, subheadline: subheadline, image_url: url}
    end
  end
end
但唯一的问题是,如果其中一个内部数组是空的,比如说
subheadline
,那么它不会追加空格并继续迭代,而是直接停在那里,所有排列都不会被处理

什么方法或途径可以帮助我


谢谢

制作一个小功能:

def maybe_add_empty_string_to_arr(arr)
  if arr == []
    [""]
  else
    arr
  end
end
然后使用以下命令调用您的循环:

maybe_add_empty_string_to_arr(headlines).each do |headline|
  maybe_add_empty_string_to_arr(subheadlines).each do |subheadline|
  ...
在你开始之前

headlines << '' if headlines.empty?
subheadlines << '' if subheadlines.empty?
image_urls << '' if image_urls.empty?

标题我选择了另一个答案,因为它更有效,尽管我是在发布问题时才意识到这一点的:)