行的替代格式,每组中有多行

时间:2016-01-13 21:35:04

标签: ruby-on-rails arrays ruby alternating

我正在用Ruby编程。

鉴于我有以下2D数组:

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

2 个答案:

答案 0 :(得分:3)

您可以使用with_indexarray decomposition和一些数学:

list.map.with_index do |(title, category), index|
  if index % (2 * cat_count) < cat_count
    [bold(title), category]
  else
    [title, category]
  end
end

答案 1 :(得分:1)

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_"或{ {1}})。

我选择使用此枚举器添加与每组""元素交替的“T”前缀,但更常规的方法是使用索引:

cat.size

使用Ruby 2.3.1,你可以写:

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"]] 

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