Skip to content

Instantly share code, notes, and snippets.

@daveio
Created April 4, 2025 09:55
Show Gist options
  • Save daveio/5db7eda7e17500ac73eecc1f0caf5149 to your computer and use it in GitHub Desktop.
Save daveio/5db7eda7e17500ac73eecc1f0caf5149 to your computer and use it in GitHub Desktop.
Claude AI adding comments to a file
#!/usr/bin/env ruby
class Person
attr_accessor :name, :age
def initialize(name, age)
@name = name
@age = age
end
def adult?
age >= 18
end
def to_s
"#{name} (#{age})"
end
end
settings = {
verbose: true,
log_level: :info,
max_connections: 5
}
people = [
Person.new("Alice", 25),
Person.new("Bob", 17),
Person.new("Charlie", 35),
Person.new("Dave", 16)
]
adults = people.select(&:adult?)
names = people.map(&:name)
non_adults = people.reject(&:adult?)
numbers = (1..10).to_a
first_three = numbers[0...3]
last_two = numbers[-2..-1]
message = <<~HEREDOC
Hello #{adults.first.name}!
We have #{adults.count} adults and #{non_adults.count} non-adults.
The adults are: #{adults.join(', ')}
HEREDOC
def do_twice
yield
yield
end
do_twice { puts "I'm in a block!" }
visits = Hash.new(0)
["google.com", "ruby-lang.org", "github.com", "ruby-lang.org"].each do |site|
visits[site] += 1
end
puts "Most visited site: #{visits.max_by { |_site, count| count }.first}"
class FlexiblePerson < Person
def method_missing(method_name, *args)
if method_name.to_s.end_with?("_info")
"#{method_name.to_s.sub("_info", "").capitalize} info for #{name}"
else
super
end
end
def respond_to_missing?(method_name, include_private = false)
method_name.to_s.end_with?("_info") || super
end
end
flexible_person = FlexiblePerson.new("Eve", 30)
puts flexible_person.medical_info
puts flexible_person.employment_info
def describe_data(data)
case data
when String
"It's a string of length #{data.length}"
when Array
"It's an array with #{data.length} elements"
when Hash
"It's a hash with #{data.keys.count} keys"
when ->(x) { x.is_a?(Numeric) && x.even? }
"It's an even number"
when ->(x) { x.is_a?(Numeric) && x.odd? }
"It's an odd number"
else
"Unknown data type"
end
end
[
"Ruby",
[1, 2, 3],
{ name: "Ruby", year: 1995 },
42,
37
].each do |item|
puts "#{item.inspect}: #{describe_data(item)}"
end
File.write("people.txt", people.map(&:to_s).join("\n"))
puts "Written to file" if File.exist?("people.txt")
(1..5)
.to_a
.tap { |arr| puts "Original array: #{arr.inspect}" }
.map { |n| n * 2 }
.tap { |arr| puts "After doubling: #{arr.inspect}" }
.select { |n| n > 5 }
.tap { |arr| puts "After selecting > 5: #{arr.inspect}" }
#!/usr/bin/env ruby
# This script demonstrates various Ruby idioms and language features
# Person class - demonstrates basic OOP concepts in Ruby
class Person
# Automatically creates getter and setter methods for name and age
attr_accessor :name, :age
# Constructor method that initializes a new Person instance
def initialize(name, age)
@name = name # Instance variable for name
@age = age # Instance variable for age
end
# Predicate method that returns true if person is 18 or older
# Note the '?' convention for methods that return boolean values
def adult?
age >= 18
end
# String representation of a Person object
# Overrides default to_s method from Object class
def to_s
"#{name} (#{age})" # String interpolation using #{}
end
end
# Hash literal syntax - demonstrates creating a configuration hash
settings = {
verbose: true, # Symbol keys using colon syntax (Ruby 1.9+)
log_level: :info, # Value can be a symbol
max_connections: 5 # Value can be a number
}
# Array of objects - demonstrates creating and initializing multiple objects
people = [
Person.new("Alice", 25), # Creating new Person instances
Person.new("Bob", 17),
Person.new("Charlie", 35),
Person.new("Dave", 16)
]
# Enumeration with higher-order methods
# select filters elements for which the block returns true
adults = people.select(&:adult?) # Symbol-to-proc shorthand for { |person| person.adult? }
# map transforms each element using the block's return value
names = people.map(&:name) # Symbol-to-proc shorthand for { |person| person.name }
# reject filters out elements for which the block returns true
non_adults = people.reject(&:adult?)
# Range and array operations
numbers = (1..10).to_a # Range converted to array: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
first_three = numbers[0...3] # Exclusive range for array slicing: [1, 2, 3]
last_two = numbers[-2..-1] # Negative indices count from the end: [9, 10]
# Here-document (HEREDOC) for multi-line strings with variable interpolation
# The <<~ syntax enables clean indentation
message = <<~HEREDOC
Hello #{adults.first.name}!
We have #{adults.count} adults and #{non_adults.count} non-adults.
The adults are: #{adults.join(', ')}
HEREDOC
# Block-accepting method definition
# The 'yield' keyword executes the block passed to the method
def do_twice
yield # Execute the block once
yield # Execute the block again
end
# Method invocation with a block
do_twice { puts "I'm in a block!" } # Block using braces syntax
# Hash with default value and array iteration
# Hash.new(0) creates a hash that returns 0 for non-existent keys
visits = Hash.new(0)
["google.com", "ruby-lang.org", "github.com", "ruby-lang.org"].each do |site|
visits[site] += 1 # Increment the count for each site
end
# Finding the key with the maximum value in a hash
# max_by returns the key-value pair with the maximum value according to the block
# _site with underscore indicates an unused parameter
puts "Most visited site: #{visits.max_by { |_site, count| count }.first}"
# Inheritance and metaprogramming with method_missing
class FlexiblePerson < Person # Inheritance using < operator
# method_missing is called when an undefined method is invoked
# This enables dynamic method creation at runtime
def method_missing(method_name, *args)
if method_name.to_s.end_with?("_info")
# Dynamically generate a response for methods ending with _info
"#{method_name.to_s.sub("_info", "").capitalize} info for #{name}"
else
# For other methods, follow normal method resolution
super # Call the parent class's method_missing
end
end
# respond_to_missing? should be defined whenever method_missing is overridden
# This makes reflection work properly with respond_to?
def respond_to_missing?(method_name, include_private = false)
method_name.to_s.end_with?("_info") || super
end
end
# Using our metaprogramming example
flexible_person = FlexiblePerson.new("Eve", 30)
puts flexible_person.medical_info # This method doesn't exist, but method_missing handles it
puts flexible_person.employment_info # Another dynamically handled method
# Pattern matching with case/when
# Demonstrates Ruby's powerful case expression capabilities
def describe_data(data)
case data
when String
"It's a string of length #{data.length}"
when Array
"It's an array with #{data.length} elements"
when Hash
"It's a hash with #{data.keys.count} keys"
when ->(x) { x.is_a?(Numeric) && x.even? } # Proc pattern matching for even numbers
"It's an even number"
when ->(x) { x.is_a?(Numeric) && x.odd? } # Proc pattern matching for odd numbers
"It's an odd number"
else
"Unknown data type"
end
end
# Iterating through a mixed array to demonstrate the pattern matching
[
"Ruby",
[1, 2, 3],
{ name: "Ruby", year: 1995 },
42,
37
].each do |item|
puts "#{item.inspect}: #{describe_data(item)}"
end
# File I/O operations
# Writing data to a file in one line
File.write("people.txt", people.map(&:to_s).join("\n"))
# Conditional expression with if as a statement modifier
puts "Written to file" if File.exist?("people.txt")
# Method chaining with tap for debugging
# tap yields the object to a block and returns the object
(1..5)
.to_a # Convert range to array
.tap { |arr| puts "Original array: #{arr.inspect}" } # Debug output without breaking the chain
.map { |n| n * 2 } # Transform each element
.tap { |arr| puts "After doubling: #{arr.inspect}" } # Another debug point
.select { |n| n > 5 } # Filter the array
.tap { |arr| puts "After selecting > 5: #{arr.inspect}" } # Final debug output
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment