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

A

alex.m.mcpherson

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?
 
W

William James

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,

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
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,756
Messages
2,569,535
Members
45,008
Latest member
obedient dusk

Latest Threads

Top