Skip to content
Tutorials Center
My learning

Topics

Lesson 131 of 134 ยท Practice

Ruby for Developers from Other Languages

A practical guide to the differences between Ruby and Python, JavaScript, Java and PHP. Truthiness, numbers, blocks, objects, errors and modules, with runnable code.

If you already program in Python, JavaScript, Java or PHP, you can read most Ruby on the first day. Loops, conditions, functions and classes all look familiar. The surprises come from a handful of design decisions that Ruby made differently, and they are exactly the ones that trip up experienced developers who translate their habits line by line.

This lesson is a map of those differences. Each section shows the Ruby behavior in a runnable example and says how the other languages differ. It is not a ranking: every language here is a sensible tool. The goal is to help you stop fighting Ruby and start writing it the way Rubyists do.

Everything is an object, and almost everything is a method call

In Java, int and Integer are different things, and in JavaScript and PHP numbers and strings are primitives that get wrapped on demand. In Ruby there are no primitives. 3 is an instance of Integer, nil is an instance of NilClass, and a class like String is itself an object. Operators are ordinary methods with special syntax: a + b is a.+(b).

Ruby Objects all the way down

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

The consequence is a uniform feel. You can call methods on a literal (5.times, "abc".reverse, nil.to_a), and you never import a helper such as Math.abs or Integer.parseInt; the method lives on the value (-5.abs, "12".to_i). Java developers will miss static utility classes less than they expect.

Truthiness: only nil and false are false

This is the single most common source of porting bugs. In Python, 0, "", [] and {} are falsy. In JavaScript, 0, "", NaN, null, undefined and false are falsy, but [] is truthy. In PHP, "0" and empty arrays are falsy too. Java does not allow non-booleans in conditions at all. Ruby has the simplest rule: only nil and false are falsy.

Ruby Truthiness table

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

When you need "is it empty?", ask for it: items.empty?, str.empty?, n.zero?. There is no implicit emptiness test, and that is on purpose. A value of 0 is a real answer, not a missing one.

Numbers: big, exact, and floor-based

Ruby integers grow as large as memory allows, so there is no overflow and no BigInteger class to remember. Division of two integers is integer division (like Java and C, unlike Python 3, JavaScript and PHP, where / gives a float). The sign rules for / and % follow Python: the result rounds toward negative infinity and the remainder takes the sign of the divisor. Java, JavaScript and PHP truncate toward zero instead.

Ruby Numbers across languages

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

There is no ++ or -- operator in Ruby; write i += 1. There is also no separate integer type for small and large numbers, and no NaN surprise from integer math: 10 / 0 raises ZeroDivisionError, while the float version 10.0 / 0 gives Infinity.

Blocks instead of loops and callbacks

In Python you write a for loop or a comprehension, in JavaScript forEach or map with an arrow function, in Java a stream, and in PHP foreach or array_map. Ruby has for, but nobody uses it. Collections have iterator methods that take a block, a chunk of code written right after the call. A block is not an object you pass as a normal argument; it is a special last argument you can yield to.

Ruby Blocks everywhere

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

If you know JavaScript, a block feels like an arrow function that you do not have to name or declare as a parameter. If you know Python, it is closer to a lambda that can hold many statements. Ruby also has real function objects: proc, lambda and ->(x) { }, plus method(:name) to turn a method into an object. See Blocks and Procs and Lambdas.

Methods: parentheses, return values and naming

Parentheses are optional in calls, the last expression is the return value, and predicate methods end in ? while dangerous or mutating ones end in !. Ruby has no function that is not a method; a def at the top level creates a private method on Object. There are no free-floating "functions" like in JavaScript, Python or PHP. Names use snake_case for methods and variables and CamelCase for classes and modules, like Python (and unlike Java or JavaScript, which use camelCase).

Ruby Method style

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

Keyword arguments are closer to Python's than to JavaScript's options-object trick or PHP's named arguments (PHP 8 added them). A missing required keyword fails with missing keyword: :host, and an unknown one with unknown keyword. Overloading by argument count or type does not exist as in Java: you use default values, keywords, or check the argument.

Classes, state and visibility

There are no public fields in Ruby. Instance variables (@name) are always private to the object, and you expose them through methods, usually generated by attr_reader, attr_writer or attr_accessor. The constructor is a method named initialize, called by new. There is no this; the receiver is self, and it is implicit when you call your own methods. Visibility is public, protected or private, and unlike Java, private means "can only be called without an explicit receiver" rather than "only in this class", so subclasses can call private methods too.

Ruby A class in Ruby

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

Notice what is missing: no type declarations, no interfaces to implement, no new keyword (it is a method call), no public static void main. Classes are open: you can reopen Account anywhere and add methods, even to built-in classes. That power is why Monkey Patching and Safe Alternatives matters.

Duck typing and modules instead of interfaces

Java has interfaces and abstract classes, PHP has interfaces and traits, TypeScript has structural types. Ruby has none of the declaration part. If an object responds to the method you call, it works. Shared behavior goes into a module, which you mix in with include. A module plays the role that interfaces with default methods, traits and mixins play elsewhere. Ruby has single inheritance for classes, plus any number of modules.

Ruby Duck typing and mixins

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

Where Java would say "this method takes a Comparable", Ruby says nothing and relies on tests and documentation. Where PHP traits copy code in at compile time, a Ruby module sits in the ancestor chain, so super works through it. See Modules and Mixins and Duck Typing and Polymorphism.

Strings, symbols and equality

Ruby strings are mutable (like PHP's and unlike Java's, JavaScript's or Python's immutable ones), so << and upcase! change the object. A symbol (:name) is an immutable, interned name, used as hash keys and as method names. There is no direct equivalent in the other four languages, though JavaScript's Symbol and Java's String.intern are distant cousins. Equality is also split into several methods: == compares values (what you want almost always, and unlike Java's ==), equal? compares identity, and eql? is what hashes use.

Ruby Strings, symbols and equality

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

Hashes are Ruby's version of the Python dict, JavaScript Map or object, Java LinkedHashMap and PHP associative array, and they keep insertion order. Keys can be any object, and the symbol-key shorthand { name: "Ada" } is the everyday form. Reading a missing key returns nil rather than throwing (use fetch for the strict version).

Errors: exceptions without declarations

Ruby uses begin ... rescue ... ensure ... end where others use try/catch/finally. There are no checked exceptions as in Java, you can rescue by class, and raise replaces throw. A def or do block can have rescue directly, without an extra begin. Errors are ordinary objects with a class hierarchy rooted at Exception, but you almost always rescue StandardError.

Ruby try/catch the Ruby way

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

Compare the modifier form value rescue fallback with JavaScript's try { } catch { }; it is handy for one-liners but catches every StandardError, so use it sparingly. There is no finally keyword (it is ensure) and no throw for errors; catch and throw exist in Ruby but mean something else (see catch and throw).

Scope and the absence of declarations

Ruby has no declaration keyword. You create a local variable by assigning to it, and it exists from that line to the end of its scope. Scopes begin at def, class and module (new, empty scope) and at blocks (nested scope that sees the outer variables). There is no hoisting like in JavaScript, no global/nonlocal as in Python, and no use clause for closures like in PHP. Constants start with a capital letter and global variables with $; both are rare.

Ruby Scope rules

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

The if false case is a famous oddity: because the parser sees the assignment, hidden exists and is nil, rather than raising a NameError. A variable that was never mentioned would raise.

A phrasebook

You would write In Ruby
for (i = 0; i < n; i++) n.times { |i| ... } or (0...n).each
list.stream().map(...) / [x*2 for x in xs] xs.map { it * 2 }
null, None, undefined nil
a ? b : c a ? b : c (same)
str.length, len(s), strlen($s) s.length or s.size
import json / require_once require "json"
x === y (JS strict equality) x == y (no type coercion between unrelated types)
print(f"{a}") / template strings puts "#{a}"
isinstance(x, T) / instanceof x.is_a?(T)
interface / trait a module, or just duck typing
static method def self.name or class << self
try/catch/finally begin/rescue/ensure

The fastest way to sound like a Rubyist is to stop writing indexes and counters. When your loop has a counter, ask which iterator does the job: map, select, each_with_index, each_slice, sum, group_by. When it builds a result with if branches, ask whether case/in or a hash lookup is clearer.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Which of these values is falsy in Ruby?

    Only nil and false are falsy. Zero, the empty string and the empty array are all truthy, unlike in Python, JavaScript (for 0 and "") and PHP.
  2. 2. What does -7 / 2 evaluate to in Ruby?

    Integer division rounds toward negative infinity, as in Python's //. Java, JavaScript's Math.trunc and PHP's intdiv would give -3.
  3. 3. What replaces Java interfaces and PHP traits in Ruby?

    A module is a bundle of methods that you mix into a class. Ruby also does not require declared interfaces: any object that responds to the method works.
  4. 4. How do you read an instance variable @name from outside the object?

    Instance variables are always private. You expose them with methods, usually generated by attr_reader, attr_writer or attr_accessor.
  5. 5. What does Ruby's ensure correspond to in other languages?

    ensure runs whether or not an exception happened, just like finally. rescue corresponds to catch, and raise corresponds to throw.

Summary

  • Everything is an object; operators are method calls; there are no primitives and no ++.
  • Only nil and false are falsy. Use empty? and zero? for emptiness tests.
  • Integers never overflow, integer division floors, and % takes the divisor's sign.
  • Iterate with methods that take blocks (each, map, select), not index loops.
  • Instance variables are private; expose them with attr_* methods. Classes are open and have single inheritance plus modules.
  • Duck typing replaces declared interfaces; modules replace traits and mixins.
  • Strings are mutable, symbols are interned names, and == compares values.
  • begin/rescue/ensure/raise replace try/catch/finally/throw, with no checked exceptions.
  • def, class and module start a fresh scope; blocks see outer variables.

Next: Ruby Interview Questions