如何将字符串整数数组转换为整数数组? Ruby

How to convert an array of string integers to an array of integers? Ruby

我有一个数组:

all_ages = ["11", "9", "10", "8", "9"]

我想将它转换为整数数组,希望能更轻松地将它们全部相加。 非常感谢任何帮助,寻找一级解决方案。

all_ages = ["11", "9", "10", "8", "9"]

代码

p all_ages.map(&:to_i).sum

或者

p all_ages.map { |x| x.to_i }.sum

输出

47

Enumerable#sum can be called with a block telling Ruby how to sum the elements of the array, in this case, to call String#to_i 首先在元素上。

all_ages = ["11", "9", "10", "8", "9"]
all_ages.sum(&:to_i)
#=> 47
     

这里有一个不同的方法可能对您的武器库有用:

all_ages = ["11", "9", "10", "8", "9"]

def sum_str_to_i (array)
  total = 0
  array.each {|x| total += x.to_i}
  total
end

sum_str_to_i(all_ages)
#=>  47

或者,如果您不想定义新方法:

total = 0
all_ages.each {|x| total += x.to_i}

total
#=>  47