如何计算文本文件中所有数字的总和
How to Calculate sum of all the digits in text file
我有文本文件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}"
但是我没有得到任何答复??
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
您的语句计算正确。只需在 File read as 之前添加 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
谢谢
我有文本文件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}"
但是我没有得到任何答复??
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
您的语句计算正确。只需在 File read as 之前添加 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
谢谢