# This is a single-line comment
=begin
This is a
multi-line comment
=end
puts "Hello, World!"
integer = 42
float = 3.14
single_quoted = 'Hello'
double_quoted = "World"
interpolation = "#{single_quoted}, #{double_quoted}!"
symbol = :my_symbol
true_val = true
false_val = false
array = [1, 2, 3, 4, 5]
hash = { "key" => "value", :symbol_key => "another value" }
# 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"
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
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
a, b = true, false
puts a && b # Logical AND: false
puts a || b # Logical OR: true
puts !a # Logical NOT: false
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
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
# 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 }
# 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
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 }
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
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
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
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
# 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
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
# 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")
# 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'
# 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