how to read file using path in ruby by function IO.readlines("path")[0] - ruby

i want to read first line of file by using following function in ruby
IO.readlines("path")[0]
But file is not in current directory, so i use path there
puts IO.readlines("Home/Documents/vikas/SHIF.doc")
but it is giving error as
a1.rb:1:in `readlines': No such file or directory # rb_sysopen - Home/Documents/vikas/SHIF.doc (Errno::ENOENT)
from a1.rb:1:in `<main>'

You can also open a file and read only the first line instead of the entire file
File.open("Home/Documents/vikas/SHIF.doc").readline

You can use File.expand_path:
puts IO.readlines(File.expand_path("Home/Documents/vikas/SHIF.doc", __FILE__))
Note however that it will create path relatively to a file directory, not to a root directory.
If you are using rails, you could use:
puts IO.readlines(Rails.root.join 'Home', 'Documents', 'vikas', 'SHIF.doc')

Related

how to use shellescape for a path with spaces in it

essentially, I have code like this (running on CentOS 6.5, ruby 2.3):
foo = "/opt/provisioning/workspace/jobs/This Has Spaces/files/thisfile.xml"
read_file_and_do_something_interesting(foo)
where we have:
def read_file_and_do_something_interesting(file_path)
data = File.read(file_path)
which leads to error:
/opt/provision/jobs/lib/aws_tools.rb:498:in `read': No such file or directory # rb_sysopen - /opt/provisioning/workspace/jobs/This Has Spaces/files/thisfile.xml (Errno::ENOENT)
So, I tried to use shellescape, like this:
read_file_and_do_something_interesting(foo.shellescape)
and still I get error:
/opt/provision/jobs/lib/aws_tools.rb:498:in `read': No such file or directory # rb_sysopen - /opt/provisioning/workspace/jobs/This\ Has\ Spaces/files/thisfile.xml (Errno::ENOENT)
So, simply, how do you use this thing?
I think this file /opt/provisioning/workspace/jobs/This Has Spaces/files/thisfile.xml really not exists.
Can you run ls "/opt/provisioning/workspace/jobs/This Has Spaces/files/thisfile.xml"?

Rake get directory name in file glob

If a Rake File exists with the following code:
file 'assets/*/map.a' => ['map.b', 'map.c'] do
# Code goes here...
end
I want to know what the name of the directory in the glob is (instead of the file). Any suggestions?
file 'assets/*/map.a' => ['map.b', 'map.c'] do |path|
File.basename(File.dirname(path))
end

How to specify a file path using '~' in 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?
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'))
When given ~ in a path at the command line, the shell converts ~ to the user's home directory. Ruby doesn't do that.
You could replace ~ using something like:
'~/.config'.sub('~', ENV['HOME'])
=> "/Users/ttm/.config"
or just reference the file as:
File.join(ENV['HOME'], '.config')
=> "/Users/ttm/.config"
or:
File.realpath('.config', ENV['HOME'])
=> "/Users/ttm/.config"

Create Directory if it doesn't exist with Ruby

I am trying to create a directory with the following code:
Dir.mkdir("/Users/Luigi/Desktop/Survey_Final/Archived/Survey/test")
unless File.exists?("/Users/Luigi/Desktop/Survey_Final/Archived/Survey/test")
However, I'm receiving this error:
No such file or directory - /Users/Luigi/Desktop/Survey_Final/Archived/Survey/test (Errno::ENOENT)
Why is this directory not being created by the Dir.mkdir statement above?
You are probably trying to create nested directories. Assuming foo does not exist, you will receive no such file or directory error for:
Dir.mkdir 'foo/bar'
# => Errno::ENOENT: No such file or directory - 'foo/bar'
To create nested directories at once, FileUtils is needed:
require 'fileutils'
FileUtils.mkdir_p 'foo/bar'
# => ["foo/bar"]
Edit2: you do not have to use FileUtils, you may do system call (update from #mu is too short comment):
> system 'mkdir', '-p', 'foo/bar' # worse version: system 'mkdir -p "foo/bar"'
=> true
But that seems (at least to me) as worse approach as you are using external 'tool' which may be unavailable on some systems (although I can hardly imagine system without mkdir, but who knows).
Simple way:
directory_name = "name"
Dir.mkdir(directory_name) unless File.exists?(directory_name)
Another simple way:
Dir.mkdir('tmp/excel') unless Dir.exist?('tmp/excel')
How about just Dir.mkdir('dir') rescue nil ?

No such file or directory

This is the error.
Atrosity [ Eric-Raios-MacBook ][ ~/dev/rubyscripts ]$ ruby script.rb
script.rb:7:in `read': No such file or directory - sent (Errno::ENOENT)
from script.rb:7:in `lSent'
from script.rb:16:in `<main>'
My Method that is causing the error is:
def lSent
$sent = Set.new(File.read("sent").split(";"))
end
lSent
If I delete this, my script runs but does not output what I want to do.
sent should be a path to a file in your server, such as
$sent = Set.new(File.read("/root/path/file.txt").split(";"))
You're attempting to read a file called "sent", but it doesn't exist in the application's path. Try including the full path to the file.

Resources