在Ruby 1.9.3中,我有一个变量包含如下所示的字符串
#HELLO
#HELLO
#HELLO
#HELLO
#WORLD
#WORLD
#WORLD
#WORLD
#FOO
#BAR
#WORLD
我想把它转换成像这样的东西:
4 times #HELLO end
4 times #WORLD end
#FOO
#BAR
#WORLD
这就是说,我希望将连续的重复字符串分组为一个,并将数量放在一边。
有没有一种聪明的方法可以使用Ruby的函数式编程能力或其他技术来做到这一点?
发布于 2012-07-03 16:52:38
试试这个:
str = "#HELLO
#HELLO
#HELLO
#HELLO
#WORLD
#WORLD
#WORLD
#WORLD
#FOO
#BAR
#WORLD"
result = ""
identical_lines = 1
str << "\n " # we need a last line to compare
str.lines.each_cons(2) do |line1,line2|
if line1 == line2
identical_lines += 1
elsif identical_lines > 1
result << "#{identical_lines} times #{line1.chomp} end\n"
identical_lines = 1
else
result << line1
end
end
puts result
此程序输出
4 times #HELLO end
4 times #WORLD end
#FOO
#BAR
#WORLD
发布于 2012-07-03 16:48:53
如果你在一个类似unix的机器上,你可能可以通过uniq -c
来传递你的输出。在此之后,您可能需要使用sed
稍微清理一下输出,但它应该相对简单。
然而,我确信也有一个整洁的纯ruby解决方案。
发布于 2012-07-03 17:02:16
如下所示:
text.each_line.each_with_object(Hash.new(0)).do |e,h|
h[e.chomp] += 1
end.each.map do |k,v|
v > 1 ? "#{v} times #{k} end" : k
end.tap do |array|
File.open(...) { |f| array.each { |e| f.puts e } }
end
https://stackoverflow.com/questions/11307211
复制相似问题