Take me home

Things you can do in Ruby

Written by August Lilleaas, published September 19, 2008

Arrays

Subtracting.

everyone = ["Jane", "Joe", "Tom", "why", "Roger"]
coming = ["Tom", "Joe"]
not_coming = everyone - coming
# => ["Jane", "why", "Roger"]

Intersection. Elements common to both arrays.

my_party = ["Jane", "Tom", "Roger", "Bob"]
jons_party = ["Warren", "Bob", "Vinnie"]
double_booked = my_party & jons_party
# => ["Bob"]

A list of words. These two statements are equivalent.

%w(Jane Joe Tom)
['Jane', 'Joe', 'Tom']

You can also escape spaces, if you really want to.

%w(foo bar\ baz)
# => ['foo', 'bar baz']

You should probably use the regular array syntax for that, though.

Strings

Formatting.

greeting = "Hello, %s. You are %d years old."
greeting % ["Roger", 5]
# => Hello, Roger. You are 5 years old.

Encrypting (one-way, irreversible)

secret_password = "peUdjGQDziI8w"
secret_password == "foo".crypt("hai")
# => false
secret_password == "foo".crypt("pepper")
# => true

Different literals.

%q{You are learning Ruby}
%Q{You are learning Ruby. You can have "double quotes" in 
here. and #{foo} interpolation. }

Hashes

Default values.

parties = {}
parties["Summer Party"]
# => nil

parties = Hash.new {|hash, key| hash[key] = [] }
parties["Summer Party"]
# => []

parties["Summer Party"] << "Roger"
parties["Summer Party"] << "Jane"
parties["Ballpen Party"] << "Bob"
parties["Completely Different"]  = 5

parties
# => {"Ballpen Party" => ["Bob", "Jane"], "Completely Different" => 5, "Summer Party" => ["Roger"]}

Shelling out

You can run system commands, too.

`which ruby` # => /usr/bin/ruby
%x{which ruby} # => /usr/bin/ruby

Further reading


Questions or comments?

Feel free to contact me on Twitter, @augustl, or e-mail me at august@augustl.com.