Need some quick help with very simple program

A

Awoke Smith

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
 

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

Forum statistics

Threads
473,764
Messages
2,569,564
Members
45,040
Latest member
papereejit

Latest Threads

Top