如何为each_char函数添加分隔符?

时间:2014-02-24 15:53:50

标签: ruby-on-rails ruby view helper

我有这个Ruby函数:

def project_total_counter
  total = Project.all.count
  spans = []
  total.to_s.each_char do |c|
    spans << content_tag(:span, c)
  end
  spans.join().html_safe
end

它产生类似于:

<span>1</span>
<span>7</span>
<span>8</span>
<span>5</span>
<span>5</span>
<span>2</span>

如何为此添加分隔符,所以我明白了:

<span>1</span>
<span>7</span>
<span>8</span>
,
<span>5</span>
<span>5</span>
<span>2</span>

感谢您的帮助。

6 个答案:

答案 0 :(得分:3)

我会使用Enumerable#each_slice执行以下操作:

def project_total_counter
  total = Project.all.count
  spans  = total.to_s.chars.each_slice(3).flat_map do |ary|
    ary.map { |c| content_tag(:span, c) }.push(",")
  end
  spans[0..-2].join().html_safe
end

答案 1 :(得分:3)

或者(假设Rails):

spans = ""
number_with_delimiter(Project.all.count, :delimiter => ',').each_char do |c|
    if c == ','
        spans << c
    else
        spans << content_tag(:span, c)
    end
end
spans.html_safe

或者,更简洁:

number_with_delimiter(Project.all.count, :delimiter => ',').each_char.inject("") do |s, c|
    s << if c == ',' then c else content_tag(:span, c) end
end.html_safe

答案 2 :(得分:1)

我认为你需要首先反转字符串,以确保你总是有三个剩余的数字,而不是像“123,45”或“123,45”那样:

如果你对正则表达式感到满意:

def project_total_counter
  results = []

  Project.all.count.to_s.reverse.gsub(/(\d{3})(?=\d)/, '\\1,').reverse.each do |char|
    results << char == "," ? "," : content_tag(:span, char)
  end

  results
end

我更喜欢@ mbratch的答案,假设您正在使用Rails。上述正则表达式的好处是它也适用于纯Ruby。

答案 3 :(得分:1)

total.to_s.each_char.map.with_index do |c, i|
  content_tag(:span, c) + (i == 2 ? ',' : '')
end.join().html_safe

答案 4 :(得分:0)

def project_total_counter
  total = Project.count
  span_groups = []
  total.to_s.each_char.in_groups_of(3) do |chars|
    span_groups << chars.map{|c| content_tag(:span, c)}.join
  end
  span_groups.join("\n,\n").html_safe
end

或更简洁

def project_total_counter
  Project.count.to_s.each_char.in_groups_of(3).map{|chars| chars.map{|c| content_tag(:span, c)}.join}.join("\n,\n").html_safe
end

请注意,您只能说Project.count而不是Project.all.count

答案 5 :(得分:0)

由于您使用的是Rails,请使用ActionView::Helpers::NumberHelper

total = Project.all.count

include ActionView::Helpers::NumberHelper
number_with_delimiter(total, delimiter: ",").each_char.map { |c|
  content_tag(:span, c)
}.join.html_safe