Ruby

James Broomfield
2 min readAug 23, 2021

When I first heard about Ruby, I was told it was quite similar to Python, the language I first learned to code in.

While undoubtedly the two are more similar to each other than to many other languages, they feel rather different to me. Admittedly this is probably at least in part due to learning better coding practices; writing decent code will always feel different to writing poor code.

A few things struck me as odd about the language, but with practice I learned to appreciate them.

Probably my favourite seemingly odd feature of Ruby is implicit returns. At first I didn’t see the point — you omit a single word and it becomes less readable. Then I discovered that if and case statements return a value in this way as well, which can result in short functions which to me seem very elegant ( if… / value1 / else / value2 / end ).

Another example is omitting parentheses in method calls. I read somewhere that for clarity’s sake it’s not recommended to omit the parentheses if you pass in parameters, which made me wonder why it was worth having this feature if it shouldn’t be used most of the time.

An answer I came to is that it’s better to create method without parameters. Emphasising Ruby’s Object Oriented focus, and in a stark contrast to functional programming, instead of passing in a value and returning a value, both values can be managed by instance variables. This can result in methods which consist entirely of method names, with no punctuation at all (def new_method / method1 / method2 / method3 / end). This, it seems to me, is the Ruby way; short, readable methods, uncluttered by needless punctuation.

Something I have wondered about is the best way to reference instance variables and methods. From inside the class an instance variable that has an attr_accessor can be referenced in three ways (@var1, var1 and self.var1). Initially I was tending to use self.var1. But then I discovered that by doing so, you are essentially taking yourself outside of the class. If you create a private method, you can’t access it using self.method1. I started avoiding using self where possible, using simply method1 for methods. For instance variable, you can use the getter method var1, but you can’t use the setter method in this way, as var1 = value would set the value to a local variable rather than calling the setter var1=. So I landed on using @var1 to access and set instance variables. Of course, if you needed to use the setter as it did something else on top of setting the value, you would have to use self.var1=.

Overall, I have enjoyed learning Ruby and thinking about how to write good Ruby, and I’m looking forward to moving on to Ruby on Rails and starting to tie the back end and front end together.

--

--