(March 2016)
first_arg = ARGV[0]
second_arg = ARGV[1]
final_arg = ARGV[-1]
ARGV[0] is not the name of the script. The full path to the current script is in $0. Get the script name only with ‘File.basename($0)’.
File.foreach('/path/to/my/file') do |line|
puts line
end
puts File.read('/path/to/my/file')
File.exists?('/path/to/my/file')
f = File.new('/path/to/my/file', 'w')
f.puts('The rain in Spain stays mainly in the plain.')
f.close
(…or, more idiomatically:)
File.open('/path/to/my/file', 'w') do |f|
f.write('The rain in Spain stays mainly in the plain.')
end
(Appending works as above, but with ‘a’ instead of ‘w’. ‘w+’ opens the file for both reading and writing.)
Dir['/path/to/recurse'].each do |f|
puts f
end
require 'find'
Find.find('/path/to/recurse') do |f|
# print file and path to screen if filename ends in .txt
puts f if f.match(/\.txt/)
end
Dir.glob('/path/to/files/*.txt').each do |f|
puts f
end
STDERR.puts "DANGER, Will Robinson!"
require 'shellwords'
Shellwords.escape("All the king's horses & all the king's men")
…which is equivalent to:
require 'shellwords'
"All the king's horses & all the king's men".shellescape
system 'echo "Hello, $USER"'
puts $? # $? is the return value; 0 for OK, non-zero for error.
now = `date`
put $?.success? # true or false
put $?.to_i
(%x{date} is the same, but allows an alternate delimeter to backticks.)
require 'open3'
cmd = 'dc'
stdin, stdout, stderr = Open3.popen3(cmd)
stdin.puts(2)
stdin.puts(2)
stdin.puts('+')
stdin.puts('p')
stdout.gets
stdin.puts('asdf')
stderr.gets
stdin.puts('p')
stdin.puts('q')
pid = spawn('tar xf foo.tar')
Process.wait pid
(Use “Process.wait” or “Process.detatch” to avoid zomblie children.)
(Forks share all existing objects, including sockets created before the fork.)
require 'socket'
parent_socket, child_socket = UNIXSocket.pair
fork do
parent_socket.close
child_socket.send("Sent from child (#{$$})", 0)
from_parent = child_socket.recv(100)
puts from_parent
end
child_socket.close
parent_socket.send("Sent from parent (#{$$}), 0)
from_child = parent_socket.recv(100)
puts from_child
% mkfifo /tmp/my_pipe
(Our writing process:)
w_pipe = open('/tmp/my_pipe', 'w+') # w+ doesn't block (?)
w_pipe.puts 'A very important message!'
w_pipe.flush
(Our reading process:)
r_pipe = open('/tmp/my_pipe', 'r+')
puts r_pipe.gets # Blocks if the pipe is empty!
% ruby -run -e httpd -- -p 8000 .
require 'socket'
httpd = TCPServer.new('localhost', 8000)
while (session = httpd.accept)
msg = (`date` + "\nHello, world.")
session.print("HTTP/1.1 200 OK\r\n" +
"Content-Type: text/plain\r\n" +
"Content-Length: #{msg.bytesize}\r\n" +
"Connection: close\r\n")
session.print("\r\n" + msg + "\r\n")
session.close
end
Write to STDERR and exit with non-zero status using “abort”:
abort 'Fatal error: lock file exists!' if File.exists?(lock_file)
if (my_string =~ /^Jan\s+(\d+).*/)
puts $1
end
my_matches = /in\s+(\w+)\s+falls/.match('The rain in Japan falls mainly...')
place = my_matches[1] # ["in Japan falls", "Japan"]
puts place # "Japan".
MY_RE = Regexp.new('\wlue') # Omit /slashes/!
puts 'We found a clue in the parlor!'.scan MY_RE # "clue"
if ('glue the vase back together'.match MY_RE)
puts "Found glue."
end