Showing posts with label Ruby. Show all posts
Showing posts with label Ruby. Show all posts

Friday, April 18, 2014

How do you create a log file with the name that of script?

require 'Date'
require 'Fileutils'
require 'Logger'

$today = Date.today.strftime("%Y%m%d")
$log = Logger.new("#{File.basename($0, '.*')}.#$today.log", 'daily')

Wednesday, April 2, 2014

Thursday, April 4, 2013

What is the difference between 'load' and 'require' in Ruby?

'require' looks for the library in all the defined search paths and also appends '.rb' or '.so' to the file name. It ensures that the library is included only once.

'load' needs the full name of the library and it gets loaded each time you call.

Wednesday, January 23, 2013

How could you comment out block of code in Ruby?

Multiple lines of text or code can be marked as comments using the Ruby "=begin" and "=end"  markers. These are known as the comment block markers.

=begin
This is a comment line.
It shows that the next line of code is
marked as a comment.
=end

Monday, January 21, 2013

What are the various ways you can run UNIX commands in Ruby?

Backticks (``) - Backticks (aka backquotes) runs the command in a sub-shell and returns the standard output from that command.

#!/usr/local/bin/ruby -w
today = `date`
puts today

System (Kernel.system) - This command runs in a subshell and returns true if the command ran successfully and false otherwise.

system "ls -1"

Exec (Kernel.exec) - It runs the given command by replacing the current process with the one created by the external command.

exec "ls -1"

spawn (available in Ruby v1.9. aka Kernel.spawn also available as Process.spawn) - It doesn‘t wait for end of the command but returns the pid of the sub-process. Therefore, you'll have to use Process.wait or Process.detach on the resulting pid.

pid = kernel.spawn ("ls -lA", {:chdir => "/home/ravi"})
Process.wait pid

%x operator - The operator makes it easy and readable to use quotes in a command.

#!/usr/bin/env ruby
list=%x[ls -1]
puts list

IO.popen - It is another way to run a command in a sub-process. It helps you control the connection to IO object between standard input and standard output in that the sub-process.

Open3.popen3 - The Ruby standard library includes the class Open3. It is easy to use and returns stdin, stdout and stderr.

Open4.popen4 - It is a Ruby Gem put together by Ara Howard. It operates similarly to open3 except that we can get the exit status from the program. It also returns a process id for the subshell and we can get the exit status from that waiting on that process.