首页 > 解决方案 > 如何对整数字符串数组求和?

问题描述

问题:将数组字符串元素转换为整数求和。我的代码:

ch = ["+7", "-3", "+10", "0"]

ch.to_i
soma = 0
string.each do |ch| 
    if ch.isdigit() 
        soma += ch.to_i
    end
end
p(soma)

错误:

Traceback (most recent call last):
main.rb:2:in `<main>': undefined method `to_i' for ["+7", "-3", "+10", "0"]:Array (NoMethodError)
Did you mean?  to_s
               to_a
               to_h

标签: arraysrubystringinteger

解决方案


而不是调用to_i这一行中的字符串数组,ch.to_i您需要调用to_i数组中的每个元素,如下所示:

numbers = ["+7", "-3", "+10", "0"]
sum = 0
numbers.each do |element| 
  sum += element.to_i
end
puts sum
#=> 14

或者简化并使用常见的 Ruby 习惯用法:

numbers = ["+7", "-3", "+10", "0"]
numbers.map(&:to_i).sum
#=> 14

推荐阅读