Things I didn't know were in Ruby

Things I didn't know were in Ruby


I’ve been muddling along with Ruby for a little while now. My primary reference has been Black’s second-edition “The Well Grounded Rubyist”. It only covers up to Ruby 2.1, which is quite old at this point - but I’ve yet to hit a major stumbling block where things have changed so much it doesn’t work. At least nothing serious enough to justify spending £30 on the third edition. Perhaps when it covers up to Ruby 3.

I’ll limit myself to three for now. But I’d like to come back to this at some point and build up a longer record of things that interest me around the language.

Immediate integers

Integer is a class, but you can’t create an instance of it as you can with String or Array. This is seemingly down to how Ruby handles small integers, which are immediate values. Immediate values aren’t stored by reference, rather, they’re stored by value. true, false, and nil are also immediate. I’ve yet to find a reason to care about this, but I can imagine there are some benefits.

Ractors

Ruby 3 comes with Ractor. It isn’t a typo of “Reactor” - rather it relates to the actor-model pattern for parallel execution. Ractors run in their own threads and have no access to objects in other Ractors. All sharing must be done with the send and receive functions. What you can share is further limited to only those objects that are thread-safe. For example, sharing strings isn’t allowed unless the string is constant.

Method Missing

I sort-of knew about this. In defining a class, you can override “method_missing” to provide more intuitive instructions to a user that may be confused about what methods your classes actually implement or expose:

class Sheriff
  def initialize(name)
    @name = name
  end

  def method_missing(m, *args)
    raise NoMethodError, "That's not in the ability of a sanitation engineer (first class)."
  end

  def clean(sewer)
    puts("Done")
  end
end

jim_dale = Sheriff.new("Marshal P. Knutt")
jim_dale.arrest("Johnny Finger")