user1368596
user1368596

Reputation:

Opening file from directory in ruby using File.open

I am relatively new to Ruby, I am trying to open a file in a way like:

#! /usr/bin/env ruby
data_file = '~/path/to/file.txt'
file = File.open(data_file, 'r')

however I get "No such file or directory" (the file does exist in that directory). It works if I put that path to the file as a command line argument such as:

#! /usr/bin/env ruby
file = File.open(ARGV[0], 'r')

and then run from the command line like: ruby script.cgi ~/path/to/file.txt

Any ideas how to get it to work the first way?

Upvotes: 6

Views: 16221

Answers (1)

Gazler
Gazler

Reputation: 84180

The path isn't getting expanded, but it does when you run it through the command line. I believe in unix systems, the path is expanded prior to running the call, meaning:

ruby file.rb ~/path/to/file

is actually expanded to

ruby file.rb /home/user/path/to/file

You can validate this by running the following in your terminal (or create a ruby file with p ARGV[0] and run that):

echo "p ARGV[0]" | ruby "" ~/path/to/file #/home/user/path/to/file

You can use File.expand_path to change ~ into /home/user

data_file = '~/path/to/file.txt'
file = File.open(File.expand_path(data_file), 'r')

Upvotes: 14

Related Questions