Topic: Need some help for a very simple program

Let's say I have a file named "data1.txt" and "data2.txt" that contain numbers on seperate lines.

data1.txt contains:
1
3
4
5
6

data2.txt contains:
3
4
6
3
2

How can ruby add the numbers on each line together from the selected file?

For instance:

Program: "Input a file name: "
User: "data2.txt"
Program: "18"

(because 3+4+6+3+2 = 18)

Program: "Input a file name: "
User: "data1.txt"
Program: "19"

(because 1+3+4+5+6 = 19)

I cannot even get passed opening a file that the user requested:

"print "Type file name: "
file_name = gets

a = []
number_file = open file_name

while x = number_file.gets
a << x
end
puts a
puts"

This would hopefully just repeat the contents of the file_name that the user inputted (I was going to worry about adding them together later)

This is what happens with the program named "p6.rb" and the data file containing the numbers named "numbers2.txt" (It contains 2 6 8 9 15 on seperate lines)

Program: "Type of a file name: "
User: "numbers2.txt"
Program: p6.rb:5:in `initialize': No such file or directory - numbers2.txt (Errno::ENOENT)
        from p6.rb:5:in `open'
        from p6.rb:5


Then I change the code to manually input the file name in the code

"a = []
number_file = open "numbers2.txt"

while x = number_file.gets
a << x
end
puts a
puts"

and I get this:

Program:
"2
6
8
9
15"

My biggest question is just how to add the numbers together for any file
that has numbers on different lines like numbers2.txt or data1.txt or
data2.txt

thank you for any reply

Re: Need some help for a very simple program

The user input will be terminated with a newline (whatever that equates to on your operating system). You will need to chomp the input to remove the newline before you pass it to the open.

Re: Need some help for a very simple program

specious is right, that's what's causing your initial problem.

awoke123 wrote:

My biggest question is just how to add the numbers together for any file
that has numbers on different lines like numbers2.txt or data1.txt or
data2.txt

Here is a possible way to do it, as a one-liner:


puts File.open(gets.chomp).lines.inject(0) {|sum, x| sum + x.to_i}

Expanded a bit with comments, probably easier to understand


# Open a file with the name of the user input
f = File.open(gets.chomp)

# .lines will give us an array of all the lines in the file (as strings)
numbers = f.lines

# Gets the total of the numbers with .inject and prints it
# We have to make sure we convert the current number being added to an integer with to_i (you can't use arithmetic on strings!)
puts numbers.inject(0) {|sum, x| sum + x.to_i}

Probably the most difficult line to grasp is the one using inject. Have a look here

http://ruby-doc.org/core/classes/Enumer … ml#M003140

if you're confused.

Hope that helps,

Alex

P.S. If you're still on Ruby 1.8.x you'll have to use readlines rather than lines.

Last edited by alexpt (2010-04-23 13:50:00)