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?
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:
is actually expanded to
You can validate this by running the following in your terminal (or create a ruby file with
p ARGV[0]and run that):You can use File.expand_path to change
~into/home/user