Sitemap
Anastasiya Soheil al-Fard

Anastasiya Soheil al-Fard

quiet person, loud life: chef. singer. scholar. writer. feminist. etc.

The Return of Saturn

2 min readMar 27, 2019
Image of Burmese ruby within white marble by thisisbossi. CC BY-SA 2.0

I came to Ruby through a tortuous, catholic path involving a visual arts major with Java/C++ requirements, and years-long stints as a web designer — or a ‘front-end developer’ in today’s parlance, a video game tester, and a line cook (that’s a story for another article). All my prior exposure to programming taught me that unless I declared a return statement in a method explicitly, it wouldn’t return anything useful.

Ruby is different.

All Ruby methods return a value, even if that value is nothing (in Ruby, nil). If a return statement is not specified in a method, the Ruby interpreter returns the value of the last line executed in that method by default. This is called implicit return, and it is taking me some time to get accustomed to. My first exposure to programming was in a language that required return types be explicitly specified in the method declaration. This is Java:

public static void main(String[] args)

main() will not return a value at all. Full stop. If I leave out the void return type, this method will not compile. And I can write other methods that won’t return anything, as long as I declare them void .

Get Anastasiya Soheil al-Fard’s stories in your inbox

Join Medium for free to get updates from this writer.

However, omission of return statements is common, if not expected, in Ruby. An example:

def sermon_on_mount
5.times {|loaf| puts loaf * 1000}
end

Without an explicit return statement, what does sermon_on_mount actually return? times is one of Ruby’s standard methods for handling loop functionality (or iterators in Ruby-speak) and it returns the integer passed to it. As this 5.times {|loaf| puts loaf * 1000} block is the last line executed in the method, sermon_on_mount returns 5 — potentially useful if I want to pass it as an argument to another method.

Here is the same method, with a different definition:

def sermon_on_mount
puts 5 * 1000
end

In this version of sermon_on_mount, puts is called in the last (and only) line of code in the method. puts is one of three Ruby standard methods for printing output to console, and all three return nil , so this method returns nil as well. If I write code that depends on this method, testing for nil input is not optional.

While implicit return may free up Ruby developers from the land of boilerplate method definitions, allowing us to solve problems in less code than might be required in other languages — it asks more of our memory and our obligation to others who might read or use our code.

--

--

Anastasiya Soheil al-Fard
Anastasiya Soheil al-Fard

Written by Anastasiya Soheil al-Fard

quiet person, loud life: chef. singer. scholar. writer. feminist. etc.