Can I return nothing in ruby?
Just for educational purpose
For example:
myarray = [1,2,3]
myarray << some_method
def some_method
if Date.today.day > 15
return "Trololo"
else
return __NOTHING__
end
end
So if today is 11'th March myarray
won't add new item. I don't want nil
- because nil
is not nothing :)
And I understand, that I can use if | unless
statement like myarray << some_method if some_method
etc. I want to understand can I return nothing or every time in ruby I am returning something (least I can get is Nil Object)
The empty?() is an inbuilt method in Ruby returns true if the set is empty or it returns false.
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.
In Ruby functions, when a return value is not explicitly defined, a function will return the last statement it evaluates. If only a print statement is evaluated, the function will return nil . The above will print the string printing , but return the string returning .
Implicit returnwhen return isn't explicitly called within a method then Ruby returns the value of the last executed instruction in the method. In the implicit_return method, as if true is always evaluated as true (mister obvious) then the last executed instruction is 42 . So the method logically returns 42 .
Basically, what you are looking for is a statement. But Ruby doesn't have statements, only expressions. Everything is an expression, i.e. everything returns a value.
No, you can't return nothing. In ruby you always return something (even if it's just nil
) - no way around that.
You can't return "nothing" from a method in ruby. As you point out you could conditionally add elements to your array. You can also invoke .compact on your array to remove all nil elements.
You can't return a real Nothing with Ruby. Everything is a object. But you can create a fake Nothing to do it. See:
Nothing = Module.new # Same as module Nothing; end
class Array
alias old_op_append <<
def <<(other)
if other == Nothing
self
else
old_op_append(other)
end
end
end
This is ugly but works in your sample. (Nothing keeps being a object.)
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