Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to specify a file path using '~' in Ruby?

Tags:

macos

ruby

If I do:

require 'inifile'

# read an existing file
file = IniFile.load('~/.config')
data = file['profile'] # error here

puts data['region']

I get an error here:

t.rb:6:in `<main>': undefined method `[]' for nil:NilClass (NoMethodError)

It goes away if I specify an absolute path:

file = IniFile.load('/User/demo1/.config')

But I do not want to hardcode the location. How can I resolve ~ to a path in Ruby?

like image 963
Anthony Kong Avatar asked Jan 09 '23 01:01

Anthony Kong


1 Answers

Ruby has a method for this case. It is File::expand_path.

Converts a pathname to an absolute pathname. Relative paths are referenced from the current working directory of the process unless dir_string is given, in which case it will be used as the starting point. The given pathname may start with a “~”, which expands to the process owner’s home directory (the environment variable HOME must be set correctly). “~user” expands to the named user’s home directory.

require 'inifile'

# read an existing file
file = IniFile.load(File.expand_path('~/.config'))
like image 165
Arup Rakshit Avatar answered Jan 16 '23 22:01

Arup Rakshit