First bit of hacked-together code, and not sure where I've gone wrong


#1

Hi there, this is my first program in any programming language, and
I’m not quite sure how to help myself learn yet, so here is my mal-
formed code:

sum = 0
print "Type the number to add up until: "
gets
chomp

for value in 1…#{$_}
sum = sum + value
end
puts sum

The error says that Ruby needs to chomp a string, but in just the
previous example in the book, chomp was used on a number. What
(presumably) simple fix will take care of this?


#2

removed_email_address@domain.invalid wrote:

sum = sum + value
end
puts sum

The error says that Ruby needs to chomp a string,

Really?

Type the number to add up until: 2
try2.rb:7:in `+’: nil can’t be coerced into Fixnum (TypeError)

It says nothing about a string or chomping.

                                              but in just the

previous example in the book, chomp was used on a number. What
(presumably) simple fix will take care of this?

Change a line to:

for value in 1…$_.to_i

Here’s how I would write it:

sum = 0
print "Type the number to add up until: "
top = gets.strip.to_i

(1 … top).each{|value|
sum += value
}

p sum