The same program in Ruby and Python
One program, two languages
This chapter takes one small task at a time and writes it twice: once in Ruby and once in Python. Both versions run in the image of this course, and the output below each one is the real run. The point is not to pick a winner; it is to see what each language makes easy, and what a reader coming from the other side should expect.
The first task is a greeting for a list of names. Ruby iterates with a block; Python iterates with a for loop and indentation.
Ruby
names = ["Ada", "Matz"]
names.each { |name| puts "Hello, #{name}" }
ruby hello.rb
Hello, Ada
Hello, Matz
Python
names = ["Ada", "Matz"] for name in names: print(f"Hello, {name}")
python3 hello.py
Hello, Ada
Hello, Matz
Same output, four lines against three. The Ruby block is one expression: the list, the method and the body in braces. The Python loop is a statement that owns the lines under it, which is why the indentation is part of the syntax rather than a style choice.
Truthiness is not the same
The difference that bites first is not syntax; it is what counts as true. Ruby has exactly two falsy values: false and nil. Python has several, and 0 is one of them.
value = 0
puts "#{value} is truthy in Ruby" if value
puts "done"
ruby truthy.rb
0 is truthy in Ruby
done
value = 0 if value: print(f"{value} is truthy in Python") else: print(f"{value} is falsy in Python")
python3 truthy.py
0 is falsy in Python
A Ruby method that returns a count and then checks it with if count works for zero; the same code in Python skips the branch. When porting, write the comparison out (count > 0) in both languages and the question disappears.
What differs
- Short blocks. Ruby sends a block to a method in one line; Python needs a loop or a generator expression. The one-liner (1..5).select(&:even?).map { |n| n * n }.sum prints 20, and so does sum(n * n for n in range(1, 6) if n % 2 == 0).
- Strings. Both interpolate values into a string: "Hello, #{name}" and f"Hello, {name}". Ruby has no separate format prefix and no r"" or b"" kinds.
- Indentation. Ruby ignores it, Python reads it. A Ruby file with four spaces instead of two still runs; a Python file with one wrong indent does not.
- Truthiness. Two falsy values against several, as above.
Neither list says one language is better. Ruby keeps a lot in the expression; Python keeps a lot in the statement. Both are consistent, and a reader who knows one can predict most of the other after a day.
Next: Text and files in both
Article author: Arthur Isaev