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.
| Habit | Ruby |
|---|---|
| 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 null | nil |
| 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:
- Only two values are falsy. false and nil; zero and the empty string are true. A Python habit of writing if items works for an empty list, but if count with zero does not.
- Everything is an object. 2 + 2 is a method call on the integer 2, so 2.class and 2.zero? both work. There are no primitive values to treat differently.
- Parentheses are optional. puts x is a call, not a variable named puts x. Ruby resolves the ambiguity by the known method name, which is why puts(x) and puts x both work and why a local variable with a method name shadows the method.
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