問題:將陣列字串元素轉換為整數求和。我的代碼:
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
uj5u.com熱心網友回復:
您需要像這樣呼叫陣列中的每個元素,而不是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
或簡化并使用常見的 Ruby 習語:
numbers = [" 7", "-3", " 10", "0"]
numbers.map(&:to_i).sum
#=> 14
uj5u.com熱心網友回復:
sum =0 l=list(input("enter the list you want to add")) for i in l: if i.isdigit(): sum=sum i else: continue print("sum of given integer strings" 和)
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/331811.html
下一篇:WordPress網站的標題布局
