qruton
qruton

Reputation: 33

open file in different directory to read lines - ruby

I've been using ARGV to open files but i feel like its clunky i want to have them in a different folder.

i want to open input.txt within my talk_parser.rb, I don't want to hardcode the file name either.

My directory (pwd is bin)

├── bin
│ └── talk_parser.rb
└── data
  └── input.txt

tried

x = Dir.glob('../data/*.txt').to_s
file = File.open(File.expand_path(x))

but i get this error

talk_parser.rb:34:in `initialize': 
No such file or directory @ rb_sysopen - /home/huvi/Desktop/test/bin/["../data/input.txt"] (Errno::ENOENT)
from talk_parser.rb:34:in `open'
from talk_parser.rb:34:in `<main>'

not sure what to do

Upvotes: 2

Views: 2430

Answers (1)

proton
proton

Reputation: 303

Dir.glob returns an Array. You can get the first element and open it:

  path = Dir.glob('../data/*.txt').first
  file = File.open(path)

Upvotes: 3

Related Questions