Question: Transform array string element to integer to sum. My code:
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)
The error:
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
CodePudding user response:
Instead of calling to_i
on the array of strings in this line ch.to_i
you need to call to_i
on each element in the array like this:
numbers = [" 7", "-3", " 10", "0"]
sum = 0
numbers.each do |element|
sum = element.to_i
end
puts sum
#=> 14
Or simplified and using common Ruby idioms:
numbers = [" 7", "-3", " 10", "0"]
numbers.map(&:to_i).sum
#=> 14
CodePudding user response:
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" sum)