Opening a file with open(ARGV.first) vs declaring a variable
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)
Published on 07 Dec 2016
by Alexander Garber
all tags
100daysofcode activerecord android annoyances api apt arch array artix atom az3w backend bash blog browser bug callback career ci-cd cli cloud code coding config configuration cp crud cryptography css csv database db design devops django docker email erp feelsgood filter fugitive gif gist git gnome gnome pomodoro grep hebrew http ide isbn-fetcher iso javascript job search js kanban kindle koans learning linkedin linux logger manjaro map markdown microservices mobi mtp neovim nodejs nvchad packages panda pastbin patch portfolio post postgres pytest python rails reduce refactoring reflections rest routes rspec ruby salesforce script scripting security sed shell sql string_replacement study tdd terminal testing tmux ttd version_control vim vim sort walkthrough webdev workflow zsh