Reputation: 13
I'm trying to read the content of a file (myfile.txt) through ARGV in Ruby. Here is my code:
filename = ARGV.first
puts "Here's your file #{filename}:"
print txt.read
What I have to do to pass the name of the file to ARGV?
Upvotes: 1
Views: 1951
Reputation: 27823
Best use
ARGF.read
Notice the spelling with an ...F
ARGF
is a stream of either all files named in the arguments, or standard input if no file has been named. This is best practice for scripts and allows your program to be used with a unix pipe.
cat filename | ruby script.rb
ruby script.rb filename
Will both work and do the same if you use ARGF
.
Upvotes: 1
Reputation: 54303
With a ruby script called read_file.rb
:
# read_file.rb
# example :
# ruby read_file.rb some_file.txt
filename = ARGV.first
puts "Here's your file #{filename}:"
print File.read(filename)
You can call :
ruby read_file.rb myfile.txt
print txt.read
txt
isn't defined. If you meant filename
, filename
is a String which contains a filename. It's not a File
object, so you cannot call filename.read
directly.
Upvotes: 1
Reputation: 134
Try the following.
file = ARGV.first
file_name_with_extn = File.basename file # => "abc.mp4"
file_extn = File.extname file # => ".mp4"
file_name = File.basename file, extn # => "abc"
file_path = File.dirname file # => "/path/"
Upvotes: 0