Ruby on rails 如何计算文本文件中所有数字的总和
我有文本文件t.txt,我想计算文本文件中所有数字的总和 范例Ruby on rails 如何计算文本文件中所有数字的总和,ruby-on-rails,ruby,ruby-on-rails-3,ruby-on-rails-4,ruby-on-rails-3.2,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代码是 ruby -e "File.read(
--- 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
seingRails
tag。如果您只使用Ruby,那么可以使用inject
。
以身作则
你的陈述计算正确。只需在文件读取之前添加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
感谢inject不起作用,它给出了错误“to_i”:没有将字符串隐式转换为整数(TypeError)”@RajeshChoudhary添加了示例:您可以使用
/\d/
而不是/\d+?/
@Stefan,这更聪明。谢谢,你只想求个位数的和。更新答案。请注意,inject
使用块的返回值,赋值是多余的。换句话说:您应该在块中使用mem+…
而不是mem+=…
。
ruby -e "puts File.read('t.txt').scan(/\d/).inject(0){|mem, obj| mem += obj.to_f}"
# => 14.0