Opening a file with open(ARGV.first) vs declaring a variable
Published on 07 Dec 2016
by Alexander Garber
I am working through Exercise 20
of Learn Ruby the Hard Way, and am trying
to make sense of the difference in output between defining the variable "current_file" and simply using open(ARGV.first):
Here is the input file test.txt:
This is line 1
This is line 2
This is line 3
Here is the beginning of the script:
input_file = ARGV.first
def print_a_line(f)
puts "#{f.gets}"
end
current_file = open(input_file)
When I call the print_a_line with the
declared variable:
print_a_line(current_file)
print_a_line(current_file)
print_a_line(current_file)
Then f.gets tracks to the new line each
time:
This is line 1
This in line 2
This is line 3
However, if I call the function with
ARGV.first:
print_a_line(open(ARGV.first))
print_a_line(open(ARGV.first))
print_a_line(open(ARGV.first))
Then f.gets does not track to the new
line and remains on line 1:
This is line 1
This is line 1
This is line 1
And the same even with input_file:
print_a_line(open(input_file))
print_a_line(open(input_file))
print_a_line(open(input_file))
f.get still doesn't track to the next
line:
This is line 1
This is line 1
This is line 1
Obviously, I would declare and use
variables -- I understand the basics of writing neat, readable code.
My question is why does f.get track to
the next line when the function is called with a declared variable and not track to the next line when called with the open(ARGV.first) or open(input_file)?
Why do I have to declare the variable
again?
current_file = open(input_file)
all tags
activerecord android annoyances api apt arch array artix atom az3w backend bash blog browser bug callback career cli cloud code coding config configuration cp crud css database db design devops django email erp filter fugitive gif gist git gnome grep hebrew http ide isbn-fetcher iso javascript job search js kanban kanban\ kindle koans linux logger manjaro map markdown microservices mobi mtp neovim nodejs packages pastbin patch post python rails reduce refactoring rest routes rspec ruby scripting security sed shell sql string_replacement study tdd terminal testing version_control vim walkthrough workflow