AI Generated Cheatsheets

Ruby Cheatsheet

Unique Features

Variables

# Local variable
x = 5

# Instance variable
@name = "John"

# Class variable
@@count = 0

# Global variable
$debug = true

Functions

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

# Method call
say_hello("Ruby")

Loops

# While loop
while x < 10 do
  puts x
  x += 1
end

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

# Each iterator
(1..5).each do |i|
  puts i
end

Conditionals

# If statement
if x > 5
  puts "x is greater than 5"
elsif x == 5
  puts "x is equal to 5"
else
  puts "x is less than 5"
end

# Ternary operator
x > 5 ? "x is greater than 5" : "x is less than or equal to 5"

File Manipulation

# Open file
file = File.open("filename.txt", "r")

# Read file
contents = file.read

# Close file
file.close

# Write to file
File.open("filename.txt", "w") do |file|
  file.write("Hello, world!")
end

Resources