File.open very basic

Hello, I’m very new to Ruby, and trying to follow the examples in
‘Beginning Ruby’ by Peter C.

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.

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.

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

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.

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.

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.

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
.
|-- linecounter
| |-- linecount.rb
| -- text.txt– text.txt
1 directory, 3 files

~/deleteme/file-test $ cd linecounter/

~/deleteme/file-test/linecounter $ ruby linecount.rb
5

~/deleteme/file-test/linecounter $ cat text.txt
1
2
3
4
5

~/deleteme/file-test/linecounter $ cd …

~/deleteme/file-test $ ruby linecounter/linecount.rb
3

~/deleteme/file-test $ cat text.txt
1
2
3

~/deleteme/file-test $ rm text.txt

~/deleteme/file-test $ ruby linecounter/linecount.rb
linecounter/linecount.rb:2:in initialize': No such file or directory - text.txt (Errno::ENOENT) from linecounter/linecount.rb:2:inopen’
from linecounter/linecount.rb:2:in `’

~/deleteme/file-test $ tree
.
-- linecounter |-- linecount.rb– text.txt