www.perdian.de Home Blog Conference talks Publications

Confessions of a Ruby convert

I have been developing applications in Java for the last 15 years. I know the language, I know the API, I know all the important frameworks and at one point I even felt arrogant enough to talk about the Java internals at conferences.

But for BetterDoc I had to use Ruby as my main programming language. I still try to sneak in a little bit of Java here and there, but Ruby is what I’m doing most of the time.

It feels a little bit like learning how to crawl again after having been an athlete. It’s a mixture between excitement, frustration, and pure embarrassment.

The story I want to write about in this post falls into the last category: pure embarrassment.

It’s funny to see and to recognize how the usage of one programming language (and one programming paradigm) influences the way of thinking. Some things simply seem too obvious to even think about it.

In my case it was something as simple as replacing parts of a String.

So let’s create a simple use case: I have a String A B C and now I want to replace B with X.

In Java it would work like this:

    String before = "A B C";
    String after = before.replaceAll("B", "X");
    System.out.println(before);   // will print "A B C"
    System.out.println(after);    // will print "A X C"

As replacing a String is a very basic functionality, it didn’t take me long to find a nice Ruby example on Stackoverflow. The code looked something like this:

    before = "A B C"
    after = before.gsub!(/B/, "X")

So far, so good. The “after” variable containes the desired value - at least that’s what I thought.

However, something weird happened that I couldn’t explain to myself: At another location where I used the before variable, suddenly the original value A B C was no longer available.

After a lot of head scratching (“what the hell is happening here?”) and frustration I finally found out, that gsub! will not create a new String with the replaced values but will change the String itself upon which the method is called. Ruby even has the nice convention of indicating that methods ending with an an exclamation mark will modify the object it’s called on.

The method I was actually looking for was gsub (without an exclamation mark) - but as every good Stackoverflow-Copy-And-Paste-Artist I didn’t take the time to fully understand what I was doing.

I learned quite a few things out of this experience:

  This article was originally posted at BetterDoc Product Development Blog
Source: https://www.perdian.de/blog/2018/11/30/confessions-of-a-ruby-convert/