Another Way to Write Ruby Code

Disclaimer: I am not suggesting to change the Ruby style guide.

At a workshop I was giving a few years ago, someone not used to writing Ruby code found an interesting way, that you can write Ruby code.

First let’s assume a class Thingy, that doesn’t do anything useful. It’s just needed to demonstrate the way to write Ruby.

Assume this is in file ‘thingy.rb’:

# frozen_string_literal: true

# Thingy is only used to demonstrate
# a way of writing Ruby code
class Thingy
  def initialize(*args)
    @args = args

  def this(other)
    @args << other

  def that(*other)
    @args << other

  def content

Now, let’s use this class in another script, that’s showing the alternative way to write Ruby code (in file use_thingy.rb):

# frozen_string_literal: true

(require_relative 'thingy')

part = ( 'String', :symbol, Math::PI)

(p ((part.this 'Wahoodie?!').that :huh, Math::E).content)

Notice that rather LISP-like way to parenthesise, in line 7 in particular. I still am surprised that this is possible in Ruby and actually behaves the way I’d expect.

Running that script yields the following output:

> ruby use_thingy.rb
["String", :symbol, 3.141592653589793, "Wahoodie?!", [:huh, 2.718281828459045]]

It’s also entertaining that Rubocop does not complain about this code:

> ls
thingy.rb     use_thingy.rb
> rubocop .
Inspecting 2 files

2 files inspected, no offenses detected

This is one of the reasons I like programming in Ruby so much: One can discover new ways (even if probably not very useful ones, sometimes) even after years of using it.

In case you’d like to experiment with this code: It’s on GitHub:

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.


%d bloggers like this: