Ruby
Ruby was created by Yukihiro "Matz" Matsumoto in 1995 with the goal of making programmers happy. It takes the "everything is an object" idea from Smalltalk, adds a friendly syntax, and lets you reshape the language itself at runtime.
Paradigm: Object-Oriented Programming
What Makes Ruby Special
- Everything is an object. Integers, strings,
niland even classes respond to methods:5.classisIntegerandnil.nil?istrue. - Blocks. A block,
{ |n| n * n }ordo ... end, is code handed to a method. It is how iteration, resource handling and callbacks are written. - Open classes. You can reopen any class, including built-in ones, and add methods. It is powerful and needs discipline.
- Metaprogramming. Methods such as
define_methodandmethod_missinglet a program create behavior as it runs. This is how Rails and many DSLs are built. - Modules as mixins. Ruby has single inheritance, and shares behavior through modules such as
EnumerableandComparable.
Example: Extending a class and chaining blocks
class Integer
def double
self * 2
end
end
puts 21.double # 42
puts 3.class # Integer
puts nil.nil? # true
[1, 2, 3, 4].select(&:even?).map { |n| n * n }.each do |n|
puts "square: #{n}"
end
How It Works
class Integerreopens the built-in class and adds adoublemethod, so21.doublereturns42.3.classandnil.nil?show that literals and evennilare objects with methods.select(&:even?)keeps 2 and 4,mapsquares them, andeachprintssquare: 4andsquare: 16.- No loop counter or index appears anywhere: iteration is expressed by sending messages to collections.
History and Where It Is Used
Ruby powers Ruby on Rails, the framework behind GitHub, Shopify and Basecamp, and tools like Homebrew, Chef and Jekyll. Ruby 3 added faster execution, pattern matching and ractors for parallelism. See the Ruby roadmap for a complete course.
Learn More
- Ruby documentation
- Ruby (Wikipedia)
- Back to Object-Oriented Programming or the PGP roadmap.