logo
eng-flag

Ruby Cheatsheet

Table of Contents

  1. Basic Syntax
  2. Data Types
  3. Variables
  4. Operators
  5. Control Flow
  6. Methods
  7. Arrays and Hashes
  8. Object-Oriented Programming
  9. Modules and Mixins
  10. Blocks, Procs, and Lambdas
  11. Exception Handling
  12. File Handling
  13. Ruby Gems and Bundler
  14. Metaprogramming

Basic Syntax

Comments

# This is a single-line comment

=begin
This is a
multi-line comment
=end

Hello World

puts "Hello, World!"

Data Types

Numbers

integer = 42
float = 3.14

Strings

single_quoted = 'Hello'
double_quoted = "World"
interpolation = "#{single_quoted}, #{double_quoted}!"

Symbols

symbol = :my_symbol

Booleans

true_val = true
false_val = false

Arrays

array = [1, 2, 3, 4, 5]

Hashes

hash = { "key" => "value", :symbol_key => "another value" }

Variables

# Local variable
local_var = "I'm local"

# Instance variable
@instance_var = "I'm an instance variable"

# Class variable
@@class_var = "I'm a class variable"

# Global variable
$global_var = "I'm global"

# Constants
CONSTANT = "I'm a constant"

Operators

Arithmetic Operators

a, b = 10, 3

puts a + b  # Addition: 13
puts a - b  # Subtraction: 7
puts a * b  # Multiplication: 30
puts a / b  # Division: 3
puts a % b  # Modulus: 1
puts a ** b # Exponentiation: 1000

Comparison Operators

x, y = 5, 10

puts x == y # Equal to: false
puts x != y # Not equal to: true
puts x > y  # Greater than: false
puts x < y  # Less than: true
puts x >= y # Greater than or equal to: false
puts x <= y # Less than or equal to: true

Logical Operators

a, b = true, false

puts a && b # Logical AND: false
puts a || b # Logical OR: true
puts !a     # Logical NOT: false

Control Flow

If-Else Statement

x = 10

if x > 0
  puts "Positive"
elsif x < 0
  puts "Negative"
else
  puts "Zero"
end

# One-line if statement
puts "Positive" if x > 0

Case Statement

grade = 'B'

case grade
when 'A'
  puts "Excellent!"
when 'B'
  puts "Good job!"
when 'C'
  puts "You passed."
else
  puts "You need to work harder."
end

Loops

# While loop
i = 0
while i < 5
  puts i
  i += 1
end

# For loop
for i in 0..4
  puts i
end

# Each loop
(0..4).each do |i|
  puts i
end

# Times loop
5.times { |i| puts i }

Methods

# Method definition
def greet(name)
  "Hello, #{name}!"
end

# Method call
puts greet("Alice")

# Method with default argument
def power(base, exponent = 2)
  base ** exponent
end

puts power(3)    # 9
puts power(3, 3) # 27

# Variable number of arguments
def sum(*numbers)
  numbers.inject(0, :+)
end

puts sum(1, 2, 3, 4, 5) # 15

Arrays and Hashes

Arrays

fruits = ["apple", "banana", "cherry"]

puts fruits[0]  # apple
fruits << "date"  # Add to the end
fruits.push("elderberry")  # Another way to add to the end
fruits.unshift("apricot")  # Add to the beginning

puts fruits.length  # 6
puts fruits.include?("banana")  # true

fruits.each { |fruit| puts fruit }

Hashes

person = { "name" => "John", "age" => 30, "city" => "New York" }

puts person["name"]  # John
person[:occupation] = "Engineer"  # Adding a new key-value pair

person.each do |key, value|
  puts "#{key}: #{value}"
end

# Symbol keys (common in Ruby)
options = { font: "Arial", size: 12, color: "blue" }
puts options[:font]  # Arial

Object-Oriented Programming

Class Definition

class Car
  attr_accessor :brand, :model

  def initialize(brand, model)
    @brand = brand
    @model = model
  end

  def start
    puts "The #{brand} #{model} is starting..."
  end
end

# Creating an object
my_car = Car.new("Toyota", "Corolla")
my_car.start

Inheritance

class ElectricCar < Car
  attr_accessor :battery_capacity

  def initialize(brand, model, battery_capacity)
    super(brand, model)
    @battery_capacity = battery_capacity
  end

  def start
    puts "The #{brand} #{model} is starting silently..."
  end
end

Modules and Mixins

module Drivable
  def drive
    puts "The vehicle is moving"
  end
end

class Car
  include Drivable
end

my_car = Car.new
my_car.drive  # The vehicle is moving

Blocks, Procs, and Lambdas

# Block
[1, 2, 3].each { |num| puts num }

# Multi-line block
[1, 2, 3].each do |num|
  puts num
end

# Proc
square = Proc.new { |x| x ** 2 }
puts square.call(5)  # 25

# Lambda
cube = ->(x) { x ** 3 }
puts cube.call(3)  # 27

Exception Handling

begin
  # Code that might raise an exception
  result = 10 / 0
rescue ZeroDivisionError => e
  puts "Cannot divide by zero: #{e.message}"
rescue StandardError => e
  puts "An error occurred: #{e.message}"
else
  puts "No exception occurred"
ensure
  puts "This always runs"
end

# Raising an exception
def check_age(age)
  raise ArgumentError, "Age cannot be negative" if age < 0
end

File Handling

# Writing to a file
File.open("output.txt", "w") do |file|
  file.puts "Hello, World!"
end

# Reading from a file
File.open("input.txt", "r") do |file|
  file.each_line do |line|
    puts line
  end
end

# Reading entire file content
content = File.read("input.txt")

Ruby Gems and Bundler

# Installing a gem
# gem install rails

# Using Bundler
# Create a Gemfile with:
# source 'https://rubygems.org'
# gem 'rails'

# Then run:
# bundle install

# In your Ruby file:
require 'bundler/setup'
require 'rails'

Metaprogramming

# Define method dynamically
class MyClass
  define_method :my_method do |arg|
    puts "Called with #{arg}"
  end
end

obj = MyClass.new
obj.my_method("Hello")  # Called with Hello

# method_missing
class MyClass
  def method_missing(method_name, *args)
    puts "You called '#{method_name}' with #{args}"
  end
end

obj = MyClass.new
obj.non_existent_method(1, 2, 3)  # You called 'non_existent_method' with [1, 2, 3]

2024 © All rights reserved - buraxta.com