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?
Any method declared void doesn't return a value. It does not need to contain a return statement, but it may do so.
Ruby methods ALWAYS return the evaluated result of the last line of the expression unless an explicit return comes before it. If you wanted to explicitly return a value you can use the return keyword.
Void functions are created and used just like value-returning functions except they do not return a value after the function executes. In lieu of a data type, void functions use the keyword "void." A void function performs a task, and then control returns back to the caller--but, it does not return a value.
Void functions do not have a return type, but they can do return values.
Put
return nil
in the last statement in method.
Or simply
nil
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With