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

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
0765080a8d48afe94f0903f7adb00c9c?d=identicon&s=25 unknown (Guest)
on 2009-01-17 04:37
(Received via mailing list)
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?
2ee1a7960cc761a6e92efb5000c0f2c9?d=identicon&s=25 William James (Guest)
on 2009-01-17 07:11
(Received via mailing list)
alex.m.mcpherson@gmail.com 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
This topic is locked and can not be replied to.