用于空值排列的 Ruby 方法/算法



我有 3 个列表:标题、副标题和image_urls。

每个列表

都是一个数组,每个列表可能包含 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,而不是附加空白并继续迭代,它只会停在那里,并且不会处理所有排列。

什么方法或方法可能对我有所帮助?

谢谢!

在开始之前,你可以

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

做一个小函数:

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|
  ...

最新更新