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

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