如何计算文本文件中所有数字的总和

时间:2015-09-30 09:33:22

标签: ruby-on-rails ruby ruby-on-rails-3 ruby-on-rails-4 ruby-on-rails-3.2

我有文本文件t.txt,我想计算文本文件中所有数字的总和 示例

    --- t.txt ---
The rahul  jumped in 2 the well. The water was cold at 1 degree Centigrade. There were 3 grip holes on the walls.  The well was 17 feet deep.
--- EOF --

总和2 + 1 + 3 + 1 + 7 我计算总和的红宝石代码是

ruby -e "File.read('t.txt').split.inject(0){|mem, obj| mem += obj.to_f}"

但我没有得到任何答案?

2 个答案:

答案 0 :(得分:4)

str = "The rahul  jumped in 2 the well. The water was cold at 1 degree Centigrade. There were 3 grip holes on the walls.  The well was 17 feet deep."

获得所有整数的总和:

str.scan(/\d+/).sum(&:to_i)
# => 23 

或者在示例中获取所有数字的总和:

str.scan(/\d+?/).sum(&:to_i)
# => 14

PS:我使用sumRails标记。如果您只使用Ruby,则可以使用inject代替。 inject

的示例
str.scan(/\d/).inject(0) { |sum, a| sum + a.to_i }
# => 14
str.scan(/\d+/).inject(0) { |sum, a| sum + a.to_i }
# => 23

答案 1 :(得分:2)

您的陈述正确计算。只需在文件读取之前添加puts:

ruby -e "puts File.read('t.txt').split.inject(0){|mem, obj| mem += obj.to_f}"
# => 23.0

仅用于汇总单个数字:

ruby -e "puts File.read('t.txt').scan(/\d/).inject(0){|mem, obj| mem += obj.to_f}"
# => 14.0

由于