Ruby Documentation
A friendly, expressive language designed for developer happiness — and the base of Ruby on Rails.
Ruby is a dynamic, object-oriented language designed for developer happiness — its code reads almost like English. Everything is an object, blocks make iteration elegant, and the Ruby on Rails framework made it famous for building web apps quickly (GitHub, Shopify and Airbnb started on Rails).
1. Introduction & Installation
- Windows: RubyInstaller (choose the version "with Devkit").
- macOS / Linux: use a version manager —
rbenvorasdf— orbrew install ruby/sudo apt install ruby-full.
ruby -v
ruby hello.rb # run a file
irb # interactive Ruby shell
gem install rails # install a gem (library)
puts "Hello, Codify!"
Output:
Hello, Codify!
⚠️ Common error:
cannot load such file -- some_gem (LoadError)— install it withgem install some_gem(or add it to theGemfileand runbundle install).
2. Basic Syntax
- No semicolons or braces for blocks —
endclosesif,def,class,do. putsprints with a newline,printwithout,pshows the inspected value (great for debugging).- Comments start with
#. Method calls don't need parentheses:puts "hi". - String interpolation works in double quotes:
"Hi #{name}".
name = "Asha"
age = 20
puts "Hi #{name}, next year you'll be #{age + 1}"
print "no newline", "\n"
p [1, "two", :three]
puts 'single quotes: #{name}'
Output:
Hi Asha, next year you'll be 21
no newline
[1, "two", :three]
single quotes: #{name}
⚠️ Common error: forgetting an
endgivessyntax error, unexpected end-of-input, expecting end.
3. Variables & Data Types
Ruby is dynamically typed; variables hold references to objects. Naming tells the scope: local, @instance, @@class, $global, CONSTANT.
| Type | Example |
|---|---|
| Integer, Float | 42, 3.14 (integers have unlimited size) |
| String | "text" (mutable) |
| Symbol | :status — an immutable, reusable name (common hash keys) |
| Boolean, nil | true, false, nil (only false and nil are falsy) |
| Array, Hash, Range | [1, 2], { name: "Asha" }, 1..5 |
count = 10
price = 99.5
title = "Ruby"
active = true
nothing = nil
status = :published
MAX = 100
puts count.class, price.class, title.class, status.class, nothing.class
puts 7 / 2, 7.0 / 2, 7 % 3, 2**100
puts "42".to_i + 1, 3.99.to_i, 10.to_s + "!", "3.5".to_f * 2
puts nothing.nil?, 0 ? "0 is truthy" : "0 is falsy"
Output:
Integer
Float
String
Symbol
NilClass
3
3.5
1
1267650600228229401496703205376
43
3
10!
7.0
true
0 is truthy
⚠️ Common error: in Ruby
0and""are truthy. Onlyfalseandnilare falsy — check.zero?or.empty?explicitly.
4. Operators
Arithmetic + - * / % **, comparison == != < > <= >= and <=> (spaceship), logical && || ! (and and/or with lower precedence), ||= (assign if nil/false), safe navigation &., ranges ../..., and === (case equality used by case/when).
puts 5 <=> 3, 2 <=> 2, 1 <=> 9
puts (1..5).include?(5), (1...5).include?(5)
puts Integer === 42, /ab/ === "cab"
cache = nil
cache ||= "computed once"
puts cache
user = nil
puts user&.name.inspect
p [1, 2] + [3] # p shows the array; puts would print each item on its own line
puts "ab" * 3
Output:
1
0
-1
true
false
true
true
computed once
nil
[1, 2, 3]
ababab
⚠️ Common error:
puts [1, 2, 3]prints1,2,3on separate lines — usepor.inspectto see the array itself. Alsoputs (a + b) * 2can parse unexpectedly; writeputs((a + b) * 2).
5. Conditional Statements
marks = 82
if marks >= 90
puts "A"
elsif marks >= 75
puts "B"
else
puts "C"
end
puts "Pass" if marks >= 40 # modifier form
puts "Not perfect" unless marks == 100
grade = case marks
when 90..100 then "excellent"
when 75...90 then "good"
else "keep going"
end
puts grade
value = 3.14
desc = case value
when Integer then "integer"
when Float then "float"
when String then "string"
end
puts desc
Output:
B
Pass
Not perfect
good
float
6. Loops & Iterators
Rubyists rarely write for loops — they use iterators with blocks.
3.times { |i| print i, " " }
puts
1.upto(4) { |i| print i, " " }
puts
10.step(1, -3) { |i| print i, " " }
puts
%w[ruby rails sinatra].each_with_index do |name, i|
puts "#{i}: #{name}"
end
n = 1
n *= 3 while n < 100
puts "n = #{n}"
(1..10).each do |x|
next if x.even?
break if x > 7
print x, " "
end
puts
Output:
0 1 2
1 2 3 4
10 7 4 1
0: ruby
1: rails
2: sinatra
n = 243
1 3 5 7
%w[a b c] is a shortcut for an array of strings. loop do ... end is an infinite loop (exit with break).
7. Methods & Blocks
def greet(name, greeting: "Hello") # keyword argument with default
"#{greeting}, #{name}!" # last expression is returned
end
def total(*prices) # splat: any number of arguments
prices.sum
end
def twice
yield
yield
end
def apply(x, &block) # capture the block as a Proc
block.call(x)
end
puts greet("Asha")
puts greet("Ravi", greeting: "Namaste")
puts total(10, 20, 30.5)
twice { print "hi " }
puts
puts apply(5) { |v| v * v }
square = ->(x) { x * x } # lambda
puts square.call(9), [1, 2, 3].map(&square).inspect
def valid_email?(s) = s.include?("@") # endless method (Ruby 3)
puts valid_email?("a@b.com")
Output:
Hello, Asha!
Namaste, Ravi!
60.5
hi hi
25
81
[1, 4, 9]
true
Conventions: methods ending in ? return booleans; methods ending in ! modify the object in place (sort!, upcase!).
8. Arrays, Hashes & Enumerable
nums = [5, 3, 8, 1, 9]
puts nums.sort.inspect, nums.max, nums.sum, nums.first(2).inspect
puts nums.select(&:odd?).inspect, nums.map { |n| n * 2 }.inspect
puts nums.reduce(:+), nums.include?(8), nums.sort.reverse.take(3).inspect
puts nums.partition { |n| n > 4 }.inspect
puts nums.each_slice(2).to_a.inspect
student = { name: "Neha", city: "Pune", marks: 85 } # symbol keys
student[:email] = "neha@example.com"
puts student[:name], student.fetch(:age, "unknown"), student.key?(:city)
student.each { |k, v| puts "#{k} => #{v}" if k != :email }
words = %w[apple banana avocado cherry blueberry]
puts words.group_by { |w| w[0] }.inspect
puts words.tally.size, words.min_by(&:length), words.sort_by { |w| [-w.length, w] }.first
counts = "mississippi".chars.tally
puts counts.inspect
Output:
[1, 3, 5, 8, 9]
9
26
[5, 3]
[5, 3, 1, 9]
[10, 6, 16, 2, 18]
26
true
[9, 8, 5]
[[5, 8, 9], [3, 1]]
[[5, 3], [8, 1], [9]]
Neha
unknown
true
name => Neha
city => Pune
marks => 85
{"a"=>["apple", "avocado"], "b"=>["banana", "blueberry"], "c"=>["cherry"]}
5
apple
blueberry
{"m"=>1, "i"=>4, "s"=>4, "p"=>2}
⚠️ Common error: mixing string and symbol keys —
h["name"]andh[:name]are different keys.
9. Object-Oriented Programming
module Greetable # module = mixin (shared behaviour)
def greet = "Hi, I'm #{name}"
end
class Account
include Greetable
include Comparable # gives <, >, ==, between? using <=>
attr_reader :name, :balance # getter methods
@@count = 0
def initialize(name, balance = 0)
@name = name
@balance = balance
@@count += 1
end
def deposit(amount)
raise ArgumentError, "amount must be positive" unless amount.positive?
@balance += amount
self # return self to allow chaining
end
def <=>(other) = balance <=> other.balance
def to_s = "#{name}: #{balance}"
def self.count = @@count # class method
end
class Savings < Account # inheritance
def initialize(name, balance, rate)
super(name, balance)
@rate = rate
end
def add_interest = deposit(balance * @rate)
end
a = Savings.new("Asha", 1000, 0.05)
b = Account.new("Ravi", 3000)
a.deposit(500).add_interest
puts a, a.greet, a < b, Account.count
puts a.is_a?(Account), Savings.ancestors.take(4).inspect
Output:
Asha: 1575.0
Hi, I'm Asha
true
2
true
[Savings, Account, Comparable, Greetable]
Also: attr_writer/attr_accessor, private/protected, Struct.new(:x, :y) and Data.define for simple value objects, and duck typing (respond_to?(:each)).
10. Advanced Concepts
Exceptions:
def parse_age(input)
Integer(input)
rescue ArgumentError => e
puts "Bad input: #{e.message}"
0
ensure
puts "checked #{input}"
end
puts parse_age("21") + parse_age("abc")
checked 21
Bad input: invalid value for Integer(): "abc"
checked abc
21
Files and JSON:
require "json"
File.write("todo.json", JSON.generate([{ task: "learn blocks", done: true }]))
data = JSON.parse(File.read("todo.json"), symbolize_names: true)
puts data.first[:task], data.size
File.delete("todo.json")
learn blocks
1
Metaprogramming and more — define_method, method_missing, send, Comparable/Enumerable mixins, lazy enumerators ((1..Float::INFINITY).lazy.select(&:even?).first(3)), and pattern matching:
config = { db: { user: "admin", port: 5432 } }
case config
in { db: { user: String => user, port: Integer => port } }
puts "#{user} on #{port}"
end
puts (1..Float::INFINITY).lazy.map { |x| x * x }.select(&:even?).first(3).inspect
admin on 5432
[4, 16, 36]
Ruby on Rails basics — Rails follows convention over configuration and MVC:
gem install rails
rails new blog
cd blog
rails generate scaffold Post title:string body:text
rails db:migrate
rails server # http://localhost:3000/posts
# app/models/post.rb
class Post < ApplicationRecord
has_many :comments, dependent: :destroy
validates :title, presence: true, length: { minimum: 5 }
end
# app/controllers/posts_controller.rb (excerpt)
def index
@posts = Post.order(created_at: :desc).limit(10)
end
Bundler manages gems per project (Gemfile + bundle install); RSpec and Minitest are the popular testing tools.
11. Examples with Output
Example 1 — Word frequency, top 3
text = "the cat and the hat and the bat"
text.split.tally.sort_by { |w, c| [-c, w] }.first(3).each { |w, c| puts "#{w}: #{c}" }
the: 3
and: 2
bat: 1
Example 2 — FizzBuzz in one expression
puts (1..15).map { |i| i % 15 == 0 ? "FizzBuzz" : i % 3 == 0 ? "Fizz" : i % 5 == 0 ? "Buzz" : i }.join(" ")
1 2 Fizz 4 Buzz Fizz 7 8 Fizz Buzz 11 Fizz 13 14 FizzBuzz
Example 3 — Two Sum with a hash
def two_sum(nums, target)
seen = {}
nums.each_with_index do |x, i|
return [seen[target - x], i] if seen.key?(target - x)
seen[x] = i
end
nil
end
p two_sum([2, 7, 11, 15], 9)
[0, 1]
12. Practice Problems
- Read a number with
gets.to_iand print its multiplication table. - Count vowels in a string using
count("aeiou"). - Given an array of hashes (students), print the topper and the class average.
- Build a
Libraryclass withadd_book,borrowandreturn_book, raising custom errors. - Write a module
Discountableand mix it intoProductandCourseclasses. - Parse a CSV file of expenses (
require "csv") and total them per category. - Create a Rails app with a
Postmodel, validations and a list/create page. - Solve the logic of Two Sum and Valid Parentheses in Ruby (submit in Python/C++/Java on Codify).
13. Interview Questions
1. What makes Ruby "purely object-oriented"?
Every value — numbers, nil, true, classes themselves — is an object with methods.
2. Symbol vs String?
Symbols (:name) are immutable and unique (one object per name), ideal as identifiers and hash keys. Strings are mutable text.
3. What is a block, Proc and lambda?
A block is code passed to a method ({ } / do...end). A Proc is a block saved as an object. A lambda is a Proc that checks argument count and returns from itself only.
4. include vs extend?
include adds a module's methods as instance methods; extend adds them as singleton (class-level) methods.
5. What does yield do?
Calls the block passed to the current method, optionally with arguments.
6. What are attr_reader, attr_writer, attr_accessor?
Shortcuts that generate getter, setter, or both methods for instance variables.
7. ==, eql?, equal??
== value equality, eql? value + type equality (used by hashes), equal? same object identity.
8. What is duck typing? Caring whether an object responds to a method rather than its class — "if it quacks like a duck".
9. What is Rails' MVC? Models (data + business rules, ActiveRecord), Views (templates), Controllers (handle requests and pick views) — wired by convention.
10. nil? vs empty? vs blank??
nil? checks for nil; empty? checks an empty string/collection; blank? (Rails) is true for nil, empty or whitespace-only.
14. Cheat Sheet & References
Basics
puts "Hi #{name}"; print "x"; p obj
name = gets.chomp; n = gets.to_i
x ||= 5; y = cond ? a : b; obj&.method
"42".to_i; 3.to_s; "3.5".to_f; :sym.to_s; "s".to_sym
Control flow
if a then b elsif c then d else e end
puts "ok" if valid; puts "no" unless valid
case x when 1..5 then "low" when String then "str" else "other" end
5.times { |i| }; 1.upto(10) { |i| }; arr.each_with_index { |v, i| }
Arrays and hashes
a = [3, 1, 2]; a << 4; a.push(5); a.pop; a.sort; a.uniq; a.flatten; a.compact
a.map { |x| x * 2 }; a.select(&:even?); a.reject(&:nil?); a.reduce(:+); a.sum; a.tally
h = { name: "Asha" }; h[:age] = 20; h.fetch(:x, 0); h.each { |k, v| }; h.keys; h.to_a
a.group_by { |x| x % 2 }; a.sort_by { |x| -x }; a.each_slice(2).to_a
Methods and classes
def add(a, b = 0, *rest, key: 1, &blk) = a + b
class User < Base; attr_accessor :name; def initialize(name) = @name = name; end
module Loggable; def log(msg) = puts(msg); end
User.new("Asha"); obj.respond_to?(:name)
Errors and files
begin; risky; rescue ArgumentError => e; puts e.message; ensure; cleanup; end
raise ArgumentError, "bad input"
File.write("a.txt", "hi"); File.read("a.txt"); File.readlines("a.txt", chomp: true)
require "json"; JSON.parse(str, symbolize_names: true); obj.to_json
Gems and Rails
# gems, bundler and rails
gem install rails
bundle install
rails new app && rails server
rails g model Post title:string && rails db:migrate
rails console
Official documentation