This page is not available in every language. Missing translations are disabled in the language selector.

Quick reference

Ruby 2.1 Feature Cheatsheet

A historical reference guide for landmark features introduced in Ruby 2.1: required keyword arguments, def method return symbols, and rational literals.

· Published

Ruby 2.1 introduced landmark syntax improvements to the language, including required keyword arguments and method definition returns.

Required Keyword Arguments

Keyword arguments without a default value become strictly required:

# length is required; char defaults to "0"
def pad(number, length:, char: "0")
  number.to_s.rjust(length, char)
end

pad(42, length: 6) # => "000042"
pad(42)            # ArgumentError: missing keyword: :length

Method Definitions Return Symbols

In Ruby 2.1+, def returns the method name as a Symbol, allowing inline modifiers:

class User
  # Make private inline
  private def secret_token
    "secret"
  end

  # Chain with module decorators
  memoize def expensive_computation
    sleep 2
    42
  end
end

Numeric & Literal Improvements

# Rational literal suffix 'r'
2/3r # => (2/3)

# Complex literal suffix 'i'
3 + 4i # => (3+4i)

# String freezing optimization: 'freeze'
"constant_string".freeze

References

Related topics