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

**URL:** <https://www.ruby-forum.com/t/first-bit-of-hacked-together-code-and-not-sure-where-ive-gone-wrong/157971>\
**Category:** Ruby\
**Created:** [January 17, 2009, 4:37am UTC](https://www.ruby-forum.com/t/first-bit-of-hacked-together-code-and-not-sure-where-ive-gone-wrong/157971 "2009-01-17T04:37:50Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![unknown](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/u/4bbf92/32.png) [@unknown](https://www.ruby-forum.com/u/unknown)\
**Post date:** [January 17, 2009, 4:37am UTC](https://www.ruby-forum.com/t/first-bit-of-hacked-together-code-and-not-sure-where-ive-gone-wrong/157971/1 "2009-01-17T04:37:50Z")

</div>

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?

---

<div class="post-metadata">

**Author:** ![unknown](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/u/4bbf92/32.png) [@unknown](https://www.ruby-forum.com/u/unknown)\
**Post date:** [January 17, 2009, 7:11am UTC](https://www.ruby-forum.com/t/first-bit-of-hacked-together-code-and-not-sure-where-ive-gone-wrong/157971/2 "2009-01-17T07:11:00Z")

</div>

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
