File.open very basic

B

Brett Kruger

Hello, I'm very new to Ruby, and trying to follow the examples in
'Beginning Ruby' by Peter Cooper

However, I'm completely stuck right at the beginning, trying to work
with File.open

I have

line_count = 0
File.open("text.txt", "r").each { |line| line_count += 1 }
puts line_count

text.txt is in the same folder as my ruby file, and is ~ 100 lines of
text. However, line_count always outputs 0 for me.

I've tried changing the syntax around, but I really have no clue what
the problem may be.
 
N

Nathan Ruska

[Note: parts of this message were removed to make it a legal post.]

Hi,

Is your text source in the same directory as the ruby file you're running?

I'm somewhat new as well, but copied/pasted what you had info a new ruby
file, and it works fine here.
 
J

jake kaiden

Brett Kruger wrote in post #992039:
line_count = 0
File.open("text.txt", "r").each { |line| line_count += 1 }
puts line_count

text.txt is in the same folder as my ruby file

very strange... what version of ruby are you running? this code
copied and pasted works for me in 1.8.7 and 1.9.2. are you absolutely
sure the .txt file is in the same directory as the program, and that
it's called "text.txt"? can't think of any other reason it wouldn't
work...

good luck,

-j
 
B

Brett Kruger

Ya I'm quite stumped as to what the problem could be. text.txt is
definitely in the same folder as my program, and I am using 1.9.2.
I tried uninstalling and reinstalling, but no luck there. I think I'll
try installing 1.8.7, and hopefully it will work there.
 
B

Brett Kruger

So I found a strange solution -

I had .rb files set to open in my text editor by default, and would
manually open them with the ruby interpreter to run them. The code
worked fine when I switched it back to opening with ruby by default.
 
J

Josh Cheek

[Note: parts of this message were removed to make it a legal post.]

Maybe your text editor doesn't run it from the same location the files are
stored in. When you say to open "text.txt" it is looking in your current
directory, Dir.pwd, not the current directory of the file
File.dirname(__FILE__).




~/deleteme/file-test $ tree
 
A

Albert Schlef

Brett Kruger wrote in post #992039:
line_count = 0
File.open("text.txt", "r").each { |line| line_count += 1 }
puts line_count

[...] line_count always outputs 0 for me.

Change the "File.open(......" line to:

puts "Last modified:", File.mtime("text.txt")
puts "Size:", File.size("text.txt")

and see if the output makes sense.
 

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

No members online now.

Forum statistics

Threads
473,996
Messages
2,570,237
Members
46,825
Latest member
VernonQuy6

Latest Threads

Top