Skip to content

Instantly share code, notes, and snippets.

@JettIsOnTheNet
Created June 17, 2024 15:29
Show Gist options
  • Save JettIsOnTheNet/ea7d48d1474414f350620bc27af436a3 to your computer and use it in GitHub Desktop.
Save JettIsOnTheNet/ea7d48d1474414f350620bc27af436a3 to your computer and use it in GitHub Desktop.
Syntax example scan sheet for Ruby.
# Ruby up to speed
# variables and const
integer_var = 10
STRING_VAR = "Hello, Ruby!"
# methods
def greet(name)
"Hello, \#{name}!"
end
# while loop
count = 5
while count > 0
puts "While loop iteration: \#{count}"
count -= 1
end
# for loop using range
for i in 1..5
puts "For loop iteration: \#{i}"
end
# each loop with array
[1, 2, 3, 4, 5].each do |num|
puts "Each loop iteration: \#{num}"
end
# conditional statements
if integer_var > 5
puts "Integer is greater than 5"
elsif integer_var == 5
puts "Integer is 5"
else
puts "Integer is less than 5"
end
# data structures
numbers = [1, 2, 3, 4, 5] # Array
info = {'name' => 'John', 'age' => 30} # Hash
# error handling
begin
result = 10 / 0
rescue ZeroDivisionError
puts "Caught a division by zero error!"
ensure
puts "This code runs no matter what"
end
# writing to a file
File.open('example.txt', 'w') do |file|
file.puts "Writing to a file in Ruby!"
end
# reading from a file
File.readlines('example.txt').each do |line|
puts "File content: \#{line}"
end
# object-oriented programming
class Point
attr_accessor :x, :y
def initialize(x, y)
@x = x
@y = y
end
def display_point
puts "Point: (\#{@x}, \#{@y})"
end
end
# main execution
puts greet("Ruby User")
point = Point.new(2, 3)
point.display_point
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment