Ruby from another language

Habits that carry over

If you already write Python, Perl or Java, most of what you know is still true in Ruby: values have types, collections hold them, a function takes arguments and returns a result. What changes is the spelling. This lesson is a map from the constructs you own to the Ruby ones, so the first script does not feel like a new alphabet.

Start with a list and a transformation. Python writes a comprehension, Java a loop or a stream, Ruby a method with a block:

numbers = [1, 2, 3] doubled = numbers.map { |n| n * 2 } puts doubled.inspect

ruby -e 'puts [1, 2, 3].map { |n| n * 2 }.inspect'

[2, 4, 6]

The same idea in Ruby

The table is the lesson. The left column is a habit from another language; the right column is the Ruby you write instead.

HabitRuby
Python [n * 2 for n in nums]nums.map { |n| n * 2 }
Python [n for n in nums if n % 2 == 0]nums.select(&:even?)
Java list.get(0)list[0], negative from the end: list[-1]
Python def f(a, b=2)def f(a, b = 2)
Perl $hash{key}hash[:key] for a symbol, hash["key"] for a string
Java System.out.println(x)puts x
Python None, Java nullnil
C-style for (i = 0; i < n; i++)n.times { |i| } or (0...n).each { |i| }

A few of these run as one-liners, and the output is the same shape you would get in Python:

ruby -e 'p (1..5).select(&:even?)'

[2, 4]

ruby -e 'p [3, 1, 2].sort'

[1, 2, 3]

ruby -e 'name = "Ada"; puts "Hello, #{name}"'

Hello, Ada

Where the habits break

Three habits from other languages cause real bugs in Ruby, and all three are quick to unlearn:

The rest of the course teaches each of these where it matters. If you want the shortest bridge from Python, lessons 71 and 72 put the same program in both languages side by side.

Next: irb beyond the prompt

Article author: Arthur Isaev