这是因为map返回一个数组。map!返回nil。然后,您将nil返回map!的内容放入temp
他们都仍然在结果的每个元素上运行块,但是当您希望将结果放入变量时,split您应该始终使用。map这是一个很容易绊倒你的微妙之处。
改变
temp = series.split(//).map!{|x| x.to_i}
到
temp = series.split(//).map{|x| x.to_i}
奖金:
您可以使用与&号和方法名称作为符号将块传递到map.
temp = series.split(//).map(&:to_i)
编辑:
根据您的评论,在将数组元素相乘时,您仍然会遇到错误。这可能是因为您的temp数组没有您认为的那么多元素。尝试使用当前没有任何内容的索引访问数组会导致nil.
temp = [1]
temp[0] #=> 1
temp[1] #=> nil
temp[0] * temp[1] #=> TypeError: nil can't be coerced into FixNum
你提到使用temp[1].to_i解决了这个问题。那是因为nil可以转换为整数。
nil.to_i #=> 0
I would check the results of temp to make sure it contains what you think it contains.
You might also want to look into Enumerable#each_slice which takes a subset of an array and processes it in a block.
nums = %w{08 02 22 97 38 15 00 40 00 75 04 05 07 78 52 12 50 77 91 08}.map(&:to_i)
nums.each_slice(4) {|a| puts a.inject(:*)}