34 comments

[ 52.3 ms ] story [ 671 ms ] thread
I've been very taken by Ruby and how it uses blocks everywhere! This is an article I wrote just to emphasize that.
Have a look at Smalltalk blocks, or FP languages, to see where Ruby's inspiration comes from.
I discovered Ruby (through Rails) about twenty years ago on the dot. Coming from Perl and PHP it took me a while, but I remember the moment when I had the same realisation you did.

I still love this language to bits, and it was fun to relive that moment vicariously through someone elses eyes. Thanks for writing it up!

Take a look at Kotlin, it perfected this idea
Is a block basically a lambda or is there more to it?
Basically. But Ruby has two types of lambdas, one called lambda, and one called proc. Blocks act like the second type.

The difference is that if return is called in the former, you return to the expression after where it is called, while I'm the latter return returns from the scope where it is defined.

This is usually going to feel reasonably intuitive, but can become weird if you e.g. reify a block into a named object and pass it around.

It can be very useful though. E.g. you can pass a block down into a recursive algorithm as a means to do a conditional early exit when a given criteria is met.

Notably you can do this even if a piece of code takes a named argument instead of a block and doesn't anticipate that use and expect you to pass a lambda instead of a process...

In most of the typical uses of a block, most people will just naturally expect the behaviour you see, because the block looks and feels like part of the scope it will return from.

Coming from a language with functions as first class objects, blocks felt a bit limited to me, because it feels as if you almost have functions but not really, and they get inputted by a back door. Used for example to:

let isLarge = a => a>100;

numbers.filter(isLarge)

Blocks let you do the same but without extracting the body as cleanly. Maybe it’s a chronological issue, where Ruby was born at a time when the above wasn’t commonplace?

>When you write 5.times { puts “Hello” }, you don’t think “I’m calling the times method and passing it a block.” You think “I’m doing something 5 times.”

I’m of two minds about this.

On the one hand, I do agree that aesthetically Ruby looks very clean and pleasing. On the other, I always feel like the mental model I have about a language is usually “dirtied” to improve syntax.

The value 5 having a method, and that method being an iterator for its value, is kinda weird in any design sense and doesn’t seem to fix any architectural order you might expect, it’s just there because the “hack” results in pretty text when used.

These magical tricks are everywhere in the language with missing_method and the like, and I guess there’s a divide between programmers’ minds when some go “oh that’s nice” and don’t care how the magic is done, and others are naturally irked by the “clever twists”.

For this audience it may be worth noting that Ruby’s blocks are closures and are passed to methods either anonymously/implicitly or as a named parameter, may be subsequently passed around to any collaborator object, or otherwise deferred/ignored, have the same range of argument arity as methods and lambdas, can even be formed from (and treated similarly to) lambdas, and are thereby fundamental to Ruby’s claim to being a multiparadigm language even as they also betray the Smalltalk roots.

In addition they have nonlocal return semantics, somewhat like a simple continuation, making them ideal for inline iteration and folding, which is how most new Rubyists first encounter them, but also occasionally a source of surprise and confusion, most notably if one mistakenly conflates return with result. Ruby does separately have callcc for more precise control over stack unwinding, although it’s a little known feature.

> can even be formed from (and treated similarly to) lambdas

They are also used to create lambdas (even the shorthand stabby-lambda syntax desugars to a call to Kernel#lambda with a block.)

> Ruby does separately have callcc for more precise control over stack unwinding, although it’s a little known feature.

callcc is included in CRuby but has been sidelined from Ruby as a language separate from CRuby as an implementation for a while, with Fibers understood to cover the most important use cases for callcc.

As someone who comes from strict languages (the more strict, the better) Ruby blocks are... not fun.

I've seen them used in situations where they are used like a callback, but due to the nature of how you write them, you have no clue whether the variable you're referring to is a local or a global one.

This makes debugging incredibly hard.

(comment deleted)
Ruby isn’t strict, no, but that’s by the by, because this doesn’t sound like a problem with blocks or how you write them. It sounds more like a problem with evals i.e. some library or framework misusing them. Blocks are closures and they straightforwardly bind variables and resolve constants/instance variables from the context of their instantiation, and resolve methods similarly because self within the block is from instantiation, when we call them normally with yield or Proc#call. Same goes for implicit contexts used for definition, if your block does a bit of metaprogramming.

If someone plays silly buggers and invokes them under instance_eval or class_exec etc that fiddle with self or definition contexts then some of this goes out the window, but those are special-purpose methods that come papered with red flags. This is typically seen in poorly designed DSLs that are trying too hard to pretend they’re not actually Ruby. If memory serves, the Chef DSL was a prime example in this regard. If the language was stricter, then sure, this wouldn’t be possible. But debugging these cases isn’t super hard either once you know the limited range of culprits, and the fix is always the same: place values in local stack variables to rely on them in a closure.

Using blocks for callbacks is fine. Don’t make assumptions about the semantics of flow control statements that other languages may have imposed on you, i.e. use next and break for explicit block results and local exit instead of return, and don’t eval them.

This level of cuteness and obsession with syntax is partly what drives me away from Ruby. A function should just be a function. We don't need to make programming languages look more like English. There are certainly issues with other languages and their verbosity (like with Java). But I don't want to have more ways to do the same thing and worry about how poetic my code reads as English - we should worry how poetic it reads as computer code.

That said, we don't need just one programming language. Perhaps Ruby is easier to learn for those new to programming and we should introduce it to students.

Blocks yield a lot more flexibility to ruby. It was the primary reason why they are so well-appreciated.
It's only more readable if you already understand it. Otherwise it is not, it requires the same kind of hand waving that happened at the start.

Important to understand that readability doesn't mean it should be closer to natural language, in programming it means that a junior dev troubleshooting that code later down the line can easily understand what's happening.

The python examples are certainly more readable from a maintainability and comprehension standpoint. Verbosity is not a bad thing at all.

With autocomplete being so good today, do we really need languages with cryptic syntax that obscure what is going on?
I believe the underlying behaviour of Ruby blocks is one of those mechanics that isn't talked about that much for newcomers, they just get used to how Ruby code look like when they see Rails, Cucumber or RSpec

Blocks and method_missing is one of those things in Ruby is what makes it so powerful! I remember watching a talk where someone was able to run JS snippets on pure Ruby just by recreating the syntax. That proves how powerful Ruby is for creating your own DSL

It's also a double edged sword and something you have to be careful with on collaborative codebases. Always prefer simplicity and readability over exotic and neat tricks, but I understand the difficulty when you have access to such a powerful tool

Market forces will ensure this system isn’t utilized regardless of how good it is. Ruby is simply to similar to Python to consider training people solely in that.

It’s a hard reality because I’m sure Ruby is better according to some criteria, but be realistic their share of the market is going to shrink until it’s not really an option of most large companies.

I know people will disagree with me, but I wish I knew earlier in my Carr how little this sort of thing matters.

This is really cute and heartwarming.

Back in the day, a lot of people including me reported feeling more comfortable in Ruby after one week than all their other languages with years of experience, as if Ruby just fits your mind like a glove naturally.

I'm glad new people are still having that "Ruby moment"

Thank you for reading this. I'm having fun learning Ruby. I just started working at a company where I use it full time. It's great learning it and I have supportive colleagues who are excited for me. I'm going to write more about Ruby. I have planned about 6 articles in the next few weeks. I hope I get around to them all.
I can’t unsee it either. Will try it later
Ruby is really let down by the tooling around the language. The language itself would be so much more fun to write if the lsp would reliably jump to the definition of functions etc that seem to appear out of no where. It has been the biggest source of frustration for me while learning Ruby.
Ruby is beautiful.

It's weird, and different and therefore a bit repulsive (at least to me it was) at first. But, once you learn it, it's so easy to read it and to understand what's going on.*

* Side-note: Sometimes variables or methods look the same as parenthesis () are optional. So, yes, there's more things that can look like magic or be interpreted in multiple ways, but more times than not, it helps to understand the code faster, because `clients` and `clients()` (variable or method) doesn't matter if all it does is "get clients" and you just need to assume what's stored/returned from that expression. Also "get clients" can be easily memoized in the method implementation so it gets as close as possible to being an actual variable.

Ruby Blocks and how they're used literally everywhere is one of the hallmarks of why it's so nice to write the first time in that language; and it shaped how I use and select future languages.

Ruby Blocks are almost certainly the reason why I love Kotlin so much - it feels like a well-typed, curly-bracket-styled Ruby in those ways. The collection operation chains in both languages just. feel. good. And I blame Ruby for my first exposure to them, and possibly a lot of people's early exposure to them that helped languages that came after become better.

Ruby does take it to a-whole-nother level though, in particular with its 'space as separator' syntax, so you can make a *robust* DSL that's even more powerful than Kotlin's "if the last param is a function, you can just put a curly bracket and go" style.

Ruby is my favorite language. There is no other language with same ergonomics. I dont understand hype around ts and all frameworks that changes every week.
Was this human-generated? Clearly it's self-submitted, and the useless "hero image" looks like lazy AI slop with Pixar characters, but did a human generate the text?
I wrote this entirely. I did use Gemini for the post image, I cannot draw and I'm not using my blog to monetize anything so I don't think there's anything wrong in AI generated images.
I heard some rumor that ruby was a type 2 lisp. There were some guys who rate programming languages on how much lisp features they reassemble. What is the source?
Ruby is still so good to read and hack things with. It is a shame that it is not so popular and you know the reasons why. I still wish with such a good DSL friendly structure, it should have become an IaC de-facto standard language or used in some niche where I could use it freely without question.
I still don’t get how

  it "adds two numbers" do
    calc = Calculator.new
    expect(calc.add(2, 3)).to eq(5)
  end
is supposed to be more readable than

  test "add two numbers":
    let calc = Calculator.new
    check calc.add(2, 3) == 5
(The latter is Nim with the std/unittest module.)
This is the first time I ever got ruby. Reading it always felt like magic to me and I think it's still too much, if I really want to understand the abstractions, which unfortunately I do. But the understanding of blocks and especially instance_eval has helped a lot.