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代码来计算总和

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

,但我没有得到任何答案?

+1

注意'inject'使用块的返回值,分配是多余的。换句话说:你应该在块中使用'mem + ...'而不是'mem + = ...'。 – Stefan

回答

2

你的说法是否正确计算。只需添加看跌之前文件的阅读:

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 

感谢

+0

没有兄弟无法正常工作,我想在我的回答中得到14个回答。 –

+0

Ohk,你只想总结一个数字。更新答案。 – Kamesh

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:我以前sum看到Rails标签。如果您只使用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 
+0

注入不工作,它给出错误“to_i”:没有将字符串隐式转换为整型(TypeError)“ –

+0

@RajeshChoudhary添加了示例。 :) – shivam

+0

Thanx shivam :) –