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

**URL:** <https://rubytalk.org/t/first-bit-of-hacked-together-code-and-not-sure-where-ive-gone-wrong/51210>\
**Category:** ruby-talk\
**Created:** [17 January 2009 03:33 UTC](https://rubytalk.org/t/first-bit-of-hacked-together-code-and-not-sure-where-ive-gone-wrong/51210 "2009-01-17T03:33:53Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![yuckysocks](https://avatars.discourse-cdn.com/v4/letter/y/ba8739/32.png) [@yuckysocks](https://rubytalk.org/u/yuckysocks)\
**Post date:** [17 January 2009 03:33 UTC](https://rubytalk.org/t/first-bit-of-hacked-together-code-and-not-sure-where-ive-gone-wrong/51210/1 "2009-01-17T03:33:53Z")

</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..#{$\_}  
&nbsp;&nbsp;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:** ![W\_James](https://avatars.discourse-cdn.com/v4/letter/w/e274bd/32.png) [@W\_James](https://rubytalk.org/u/W_James)\
**Post date:** [17 January 2009 06:08 UTC](https://rubytalk.org/t/first-bit-of-hacked-together-code-and-not-sure-where-ive-gone-wrong/51210/2 "2009-01-17T06:08:59Z")

</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..#{$\_}  
> &nbsp;&nbsp;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.

> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;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|  
&nbsp;&nbsp;sum += value  
}

p sum

> **···**
>
> alex.m.mcpherson@gmail.com wrote:
