What is a singleton class in Ruby?

What are singleton classes in Ruby? Why do we need them? Or rather what (language design) problem do they solve? Side note: singleton classes are also known as meta classes or eigen classes. In case you've heard those terms. To get at the motivation for singleton classes in Ruby, first…

Include vs. Extend, what's the difference?

What is the difference between include vs. extend in Ruby? And how do we know which one to use? (Note: the explanation below mentions singleton classes. For now think of a singleton class (aka metaclass or eigenclass) as a place where class methods are 'held'. As opposed to instance methods…

What is method_missing? Examples of metaprogramming in Rails ActiveSupport

Have you ever wondered why we can write Rails.env.production? instead of having to check with equals like Rails.env == "production"? We'll take a little tour of ActiveSupport code to answer this question about method calls and method_missing. Specifically the StringInquirer class, which is behind this…

Does using `freeze` prevent changing the value of ruby constants?

One of my students recently asked about the freeze method in Ruby (as it came up in one of their interviews). So we popped into an irb session. And well...I was surprised. (I've internalized this about learning: when you're surprised, when your predictions don't come true about how something…

How do constants work in ruby?

When you hear the word a constant, what comes to mind? What would you tell someone what a constant is, in a programming language? A constant is a variable whose value cannot be changed once assigned. Right? This is true for most programming languages, in Ruby there is more to…

How do ruby objects and instance variables work?

Ruby is an object oriented language and has classes and objects and methods and instance variables and all those things. But if you are coming from other object oriented languages like Java, there are a few surprising things about how Ruby objects work that are useful to know. Here are…

RailsUJS vs. Mrujs vs. Request.js

Rails 7 officially removed including rails-ujs by default. So does that mean we should stop using rails-ujs then? And what are Mrujs and Request.js? In this quick post, I answer those questions. Let's start with a quick summary of what rails-ujs all about: rails-ujs is a rewrite of the…

Active Record includes and N + 1 Query Problem

Consider the following code books = Book.limit(10) books.each do |book| puts book.author.last_name end In the above code, a query is made each time the lastname of an author of a book is needed in puts book.author.last_name. A single query for each book.…