行的交替格式,每组多行

Alternate formatting of rows, with multiple rows in each set

我正在 Ruby 编程。

鉴于我有以下二维数组:

list = [
  ["T1", "Cat 1"],
  ["T2", "Cat 2"],
  ["T3", "Cat 3"],
  ["T4", "Cat 4"],
  ["T5", "Cat 1"],
  ["T6", "Cat 2"],
  ["T7", "Cat 3"],
  ["T8", "Cat 4"],
  ["T9", "Cat 1"],
  ["T10", "Cat 2"],
  ["T11", "Cat 3"],
  ["T12", "Cat 4"],
]

我还有一个类别列表:

cat = ["Cat 1", "Cat 2", "Cat 3", "Cat 4"]
cat_count = cat.count

我还有方法bold,将文本格式化为粗体,为了简单起见,我将使用下面的方法:

def bold(text)
  'b_' << text
end

我想以交替方式格式化每组类别。所以第一组是粗体,然后第二组不是,第三组是粗体,第四组不是等等

在这种情况下,我会得到以下格式化输出: T1 T2 T3 T4 T5 T6 T7 T8 T9 T10 T11 T12

我希望得到以下 ruby 输出:

["b_T1", "Cat 1"]
["b_T2", "Cat 2"]
["b_T3", "Cat 3"]
["b_T4", "Cat 4"]
["T5", "Cat 1"]
["T6", "Cat 2"]
["T7", "Cat 3"]
["T8", "Cat 4"]
["b_T9", "Cat 1"]
["b_T10", "Cat 2"]
["b_T11", "Cat 3"]
["b_T12", "Cat 4"]

我目前有以下代码,看起来一点也不 Rubyist。请帮助我改进此代码。

cat_increment = 0
switch = 1

list.map do |l|
  cat_increment+=1
  entry = switch ? [bold(l.first), l.second] : l
  if cat_increment == cat_count
    switch = switch ? nil : 1
    cat_increment = 0
  end 
  entry
end

您可以使用 with_index, array decomposition 和一些数学:

list.map.with_index do |(title, category), index|
  if index % (2 * cat_count) < cat_count
    [bold(title), category]
  else
    [title, category]
  end
end
enum = [*["b_"]*cat.size, *[""]*cat.size].cycle
  #=> #<Enumerator: ["b_", "b_", "b_", "b_", "", "", "", ""]:cycle>
list.map { |t,c| [enum.next+t, c] }
  #=> [["b_T1", "Cat 1"], ["b_T2", "Cat 2"], ["b_T3", "Cat 3"], ["b_T4", "Cat 4"],
  #    ["T5", "Cat 1"], ["T6", "Cat 2"], ["T7", "Cat 3"], ["T8", "Cat 4"],
  #    ["b_T9", "Cat 1"], ["b_T10", "Cat 2"], ["b_T11", "Cat 3"], ["b_T12", "Cat 4"]] 

Array#cycle 用于将数组 ["b_", "b_", "b_", "b_", "", "", "", ""] 转换为无限重复的枚举数。

然后只需将 list 的每个元素映射到一个新值,其中 "T" 字符串前面加上 enum 的下一个元素("b_""").

我选择使用此枚举器来添加 "T" 前缀,这些前缀与每组 cat.size 元素交替出现,但更传统的方法是使用索引:

list.map.with_index { |(t,c),i| [(i/4).even? ? "b_"+t : "t", c] } 
  #=> [["b_T1", "Cat 1"], ["b_T2", "Cat 2"], ["b_T3", "Cat 3"], ["b_T4", "Cat 4"],
  #    ["T5", "Cat 1"], ["T6", "Cat 2"], ["T7", "Cat 3"], ["T8", "Cat 4"],
  #    ["b_T9", "Cat 1"], ["b_T10", "Cat 2"], ["b_T11", "Cat 3"], ["b_T12", "Cat 4"]] 

使用 Ruby 2.3.1 你将能够写:

list.each_with_index { |(t,_),i| print "#{ (i/4).even? ? t.boldify : t } " }

T1 T2 T3 T4 T5 T6 T7 T8 T9 T10 T11 T12