Ruby 项目任务17。从一系列数字中查找所有字母的编号

Ruby 项目任务17。从一系列数字中查找所有字母的编号,ruby,loops,foreach,Ruby,Loops,Foreach,问题是: 如果数字1到5是用文字写出来的:一、二、三、四、五,那么总共使用了3+3+5+4+4=19个字母。 如果所有从1到1000(一千)的数字都是用文字写出来的,那么会使用多少个字母 我的解决方案: require 'humanize' arr, total = [], 0 (1..1000).to_a.map(&:humanize).each {|x| arr << x.delete(" ").delete("-")}.map {|y| total += y.lengt

问题是:

如果数字1到5是用文字写出来的:一、二、三、四、五,那么总共使用了3+3+5+4+4=19个字母。 如果所有从1到1000(一千)的数字都是用文字写出来的,那么会使用多少个字母

我的解决方案:

require 'humanize'
arr, total = [], 0
(1..1000).to_a.map(&:humanize).each {|x| arr << x.delete(" ").delete("-")}.map {|y| total += y.length }
p total
为什么我的解决方案是错误的?据我所知,这两个实现应该提供相同的输出

编辑: 又发现了一件奇怪的事。 如果我将1000改为最多20的任意数字,实现如下所示:

(1..20).to_a.map(&:humanize).each {|x| arr << x.delete(" ").delete("-")}.map {|y| total += y.length }

p (1..20).to_a.map(&:humanize).join.tr(" -", "").size

(1..20).映射(&:人性化)。每个{x | arr你的问题是你把
映射
每个
搞混了

(1..1000).to_a.map(&:humanize)
              .each {|x| arr << x.delete(" ").delete("-") } # ??? each
              .map {|y| total += y.length }                 # ??? map
或者,更具ruby风格:

(1..1000).to_a.map(&:humanize)
              .map { |x| x.delete(" ").delete("-") }
              .reduce(:+) # reduce by summing everything up
或者,更好的(
to_a
在这里是多余的):


您也可以将
放在a
上。@sagarpandya82是的,的确,这部分只是复制粘贴的。Thx将更新“甚至更好”部分,使原始答案尽可能接近问题。
(1..1000).to_a.map(&:humanize)
              .map { |x| x.delete(" ").delete("-") } # sic!, no need for arr
              .each { |y| total += y.length } # no need to map here
(1..1000).to_a.map(&:humanize)
              .map { |x| x.delete(" ").delete("-") }
              .reduce(:+) # reduce by summing everything up
(1..1000).map(&:humanize)
         .reduce(0) { |memo, x| memo + x.delete(" ").delete("-").length }