Some Ruby
3/2/26
Its been a while since I’ve dipped my toes in any language that hasn’t been Python, JS, or SQL so the other day I decided to pick a new programming language and give it a try. I picked Ruby because I know that Rails is a very popular web framework and I’m a huge fan of the REWORK podcast which frequently has the creator of the framework as a guest (DHH).
Here’s a simple Person class in ruby:
class Person
def initialize(name)
@name = name
end
def say_hi
puts "Hello, #{@name}"
end
end
if __FILE__ == $0
me = Person.new('anthony')
me.say_hi
me.say_hi() # parentheses optional
puts me.name # this will fail
end
A few things stood out to me after a few hours:
- Code blocks end with the
endkeyword which is taking some getting used to, BUT I do like how it looks, that extra word adds some visual closure that Python doesn’t provide. - Parentheses are optional
- Methods can have
!and?in them!! For example, there is anempty?method:
def mark_item_complete(name)
to_change = @items.select { |item| item[:name] == name}
if to_change.empty?
raise ItemDoesntExist, "No item for #{name}"
end
to_change.each do |entry|
# ":done" is a symbol in Ruby
entry[:done] = true
end
end
- One of my favorite methods I’ve come across is called
partition, which will split an array into an array where a condition is true and an array where the condition is false:
items = ['Anthony', 'likes', 'keyboards']
removed, kept = items.partition { |item| item.length > 5}
puts removed # ['Anthony', 'keyboards']
puts kept # ['likes']
- Its duck typed and the
respond_to?method is a popular way to prevent errors, for example:
class Dog
def bark
puts "Woof!"
end
end
class Wolf
def bark
puts "WOOF"
end
end
class Chicken
end
if __FILE__ == $0
animals = [Dog.new, Wolf.new, Chicken.new, 1]
animals.each do |animal|
if animal.respond_to? 'bark'
animal.bark
else
puts "...silence..."
end
end
end
I’ve got a repo with a basic CLI todo app here but my broader goal is to work up to Rails and deploy a basic todo app to get a feel for what that’s like.
Back to the mine (lol)!!!