Syntax Basics and Conventions
BEGIN END __ENCODING__ __END__ __FILE__ __LINE__ alias and begin break case class def defined?
3.1 Statements and Comments
# Single-line comment
=begin
Multi-line comment (rarely used)
=end
x = 5; y = 10 # semicolons separate statements on one line (uncommon)
total = x +
y # line continues after an operator
long = [1, 2, 3]
.map { |n| n * 2 } # leading-dot method chains are allowed3.2 Naming Conventions
Local variables, methods user_name, calculate_total Classes, modules UserAccount, HTTPClient empty?, valid? Dangerous/mutating methods sort!, save!
3.3 Everything Is an Expression
Methods return their last evaluated expression (no explicit return needed).
result = if score > 50 then "pass" else "fail" end
value = begin
compute
rescue StandardError
0
end
def add(a, b) = a + b # endless method (Ruby 3.0+)3.4 Optional Parentheses
Convention: omit parentheses for DSL-like calls and simple statements (puts, require, attr_accessor), and keep them when there are arguments in expressions.
puts "hello"
puts("hello")
add 2, 3
add(2, 3)
[1, 2, 3].include? 23.5 Keywords
BEGIN END __ENCODING__ __END__ __FILE__ __LINE__ alias and begin break case class def defined? do else elsif end ensure false for if in module next nil not or redo rescue retry return self super then true undef unless until when while yield
3.6 Magic Comments and __END__
# frozen_string_literal: true # all string literals in this file are frozen (recommended)
# encoding: utf-8 # default since Ruby 2.0
puts DATA.read # reads the text after __END__
__END__
This text is accessible via the DATA constant.