Tuesday, December 16, 2008

Ruby Snippets

As I get deeper into the Ruby world, it is helpful to have a few snippets of working code and syntax for common tasks to copy as needed. I expect to add to this tiny reference over time.

updated July 9, 2008 to add a one liner to remove DOS line endings from a text file.

Formatting numbers

To format numbers, use the sprintf method.

x = 1.00
puts "x is $" + sprintf("%#0.2f", x)
puts "x is " + sprintf("%#2d", x)

The output is:

x is $1.00
x is 1

The defined? method

The defined? method can be used on any object to see if it exists.

x = 1
if defined? x
puts "x is defined"
end

Case statements

Case statements are a more elegant way to handle a large number of conditions than using nested if statements.

x = 3
case x
when "1"
result = "x is 1"
when "2"
result = "x is 2"
when "3"
result = "x is 3"
else
result = "x is something else"
end

Substrings

Ruby has (at least) two ways to reference parts of a string object. One is to use the slice method:

x = "abcde"
y = x.slice(0,1)
The result is y = "a".
x = "abcde"
y = x.slice(-1,1)
The result is y = "e".
x = "abcde"
y = x.slice(2,3)
The result is y = "cde".

The second way is to treat the string object as an array of characters like the C programming language.

x = "abcde"
y = x[2,3]
The result is y = "cde".

One liner to edit a file in place

These one liners are also in the general Ruby article.

This command edits a file in place, performing a global text search/replace. The -p switch tells ruby to place your code in the loop while gets; ...; print; end. The -i tells ruby to edit files in place, and -e indicates that a one line program follows.

ruby -p -i -e '$_.gsub!(/248/,"949")' file.txt

One liner to remove DOS line endings from a file

A Unix or Mac text file uses a single line feed character to mark the end of a line (hex 0A). Files created on DOS or Windows use two characters, carriage return and line feed (hex 0D 0A). This command edits a file in place, removing the carriage returns.

ruby -p -i -e '$_.gsub!(/\x0D/,"")' file.txt

One liner to edit files in place and backup each one to *.old

ruby -p -i.old -e '$_.gsub!(/248/,"949")' *.txt