A guide to Ruby in ten lines of code

This is a slightly unorthodox introduction guide to the Ruby language. Through this guide we will examine just ten one-line snippets of code, and discover a lot of features from each of them.

This is the post version of a talk I gave for LibreIM.


puts "Hello #{gets.strip}!"

This snippet accepts a string from standard input, then cleans the leading and trailing spacing characters and embeds it in a greeting which is shown on standard output. Notice that:

puts "boooored".upcase unless Time.now.saturday?

This example is so readable you probably don’t need a description. Notice that:

real, imag = (1 + 3i).rectangular

This snippet assigns the real part of 1 + 3i to real and the imaginary part to imag. Notice that:

Object oriented programming

class DeadPlayerError < StandardError; end

Defines a class useful to return errors (exceptions). Notice that:

Point = Struct.new :x, :y, :z

Creates a class with getters and setters for the given attributes. Notice that:

Iteration and data structures

puts %w[such elegant wow].each_with_index.map { |w,i| "#{i}. #{w}" }

Walks through the array, obtains an array of strings index. element and prints it on stdout. Notice that:

dot = ->(v1, v2) { v1.zip(v2).reduce(0) { |p, (n, m)| p + n * m } }

Computes the dot product. Example usage: dot.([1, 2, 3], [-1, 0, 2]). Notice that:

fib = Hash.new { |h, i| h[i] = h[i - 2] + h[i - 1] }.update(0 => 0, 1 => 1)

Creates a Hash which contains, for each index, the corresponding term of the Fibonacci sequence. Notice that:

solution.neighborhood.detect { |attempt, fitness| fitness > @current_fitness }

Assuming the .neighborhood returns a collection of possible solutions and their performance (fitness), this finds the first one which improves the current solution. Actual use: https://git.io/vPxQ6. Notice that:


open(DATA.read, "w").write IO.read($0).gsub(/^#' /, "")

This snippet reads itself (as in, the own program running), uncomments lines marked with #' and passes the result as input to the program started by Kernel#open. Notice that:

The catch The program is hidden in the data section of the original script:

|pandoc -t beamer -o slides.pdf --pdf-engine=xelatex