7
votes

My experience is in C-based languages (C, C++, Java, C#) where the return type of a function can be void, i.e no return. But in Ruby, it appears that every function returns something. I was wondering what to return in Ruby for a method that wouldn't return anything in Java or C++. My best guesses would be either nil or the object that contains the method (for chaining) or just ignore whatever happens to be at the end, but I can't seem to find any information on this.

What's an alternative to void in Ruby?

3

3 Answers

10
votes

Put

return nil

in the last statement in method.

Or simply

nil
1
votes

nil is not the same as void. You can set a variable to nil, but you cannot set it to void. If a function returns nil it can be assigned to a variable with no error, but try that with a void function (in java or some such language that supports void functions) and the compiler will bark. I'm not a ruby super-expert, but I can find no indication that the concept of void is supported. All functions return something, even if it's nil. If this is incorrect then I hope someone with more knowledge of ruby can provide a counterexample.

A variable, especially in ruby where everything is an object, is a thing with a name and a place to store an address that points to an object somewhere on the heap. Setting a variable to nil means setting its pointer to the one and only instance of NilClass. (true and false are similar; there are single instance of TrueClass and FalseClass.)

I realize that C has a thing called void pointers. This is an entirely different use of the word "void". A void pointer does in fact contain an address and point to something. Let's ignore these for now; I'm only mentioning them to head off unfruitful retorts. We're focusing on functions in ruby that literally return nothing, which do not exist as far as I can tell.

0
votes

If you want nothing to be returned, yes you can use return nil . But why?

By not assigning a function call to a variable, you can blissfully forget what has been returned. That returned value will be stored no where and will be lost in garbage collection.