如何对整数字符串数组求和?

-1 ruby arrays string integer

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

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)
Run Code Online (Sandbox Code Playgroud)

错误:

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
Run Code Online (Sandbox Code Playgroud)

spi*_*ann 7

您需要像这样调用to_i数组中的每个元素,而不是调用此行中的字符串数组:ch.to_ito_i

numbers = ["+7", "-3", "+10", "0"]
sum = 0
numbers.each do |element| 
  sum += element.to_i
end
puts sum
#=> 14
Run Code Online (Sandbox Code Playgroud)

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

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

  • 或者 `numbers.sum(&amp;:to_i)` (9认同)