Here’s a Ruby cheat sheet with Ruby syntax and commonly used commands:
Variables
name = "John"
age = 25
Data Types
Strings:
greeting = "Hello, World!"
Numbers:
integer_number = 42
float_number = 3.14
Arrays:
numbers = [1, 2, 3, 4, 5]
Hashes:
person = { name: "Alice", age: 30 }
Control Flow
If-Else:
if condition
# code to run if the condition is true
else
# code to run if the condition is false
end
While Loop:
while condition
# code to repeat as long as the condition is true
end
For Loop:
for i in 1..5
# code to run for each iteration
end
Methods
def greet(name)
puts "Hello, #{name}!"
end
greet("Bob")
Classes and Objects
class Dog
attr_accessor :name, :age
def initialize(name, age)
@name = name
@age = age
end
def bark
puts "Woof!"
end
end
my_dog = Dog.new("Buddy", 3)
my_dog.bark
File I/O
Read from a File:
File.open("example.txt", "r") do |file|
contents = file.read
puts contents
end
Write to a File:
File.open("example.txt", "w") do |file|
file.puts "Hello, Ruby!"
end
Exception Handling
begin
# code that might raise an exception
rescue SomeException => e
puts "An error occurred: #{e.message}"
end
Symbols
# Symbols are lightweight strings often used as keys in hashes
status = :success
Enumerable Methods
Each:
numbers.each { |num| puts num }
Map:
doubled_numbers = numbers.map { |num| num * 2 }
Select:
even_numbers = numbers.select { |num| num.even? }
Regular Expressions
pattern = /\d+/
result = "123 Ruby".match(pattern)
puts result[0] # Output: 123
Installing Gems
gem install gem_name
Using Gems
require 'gem_name'
This is a basic cheat sheet, and Ruby has many more features and nuances. For in-depth learning, refer to the official Ruby documentation.