Can I return nothing in ruby?
Just for educational purpose
For example:
myarray = [1,2,3]
myarray << some_method
def some_method
Nothing does not mean anything to ruby from what i know :) You can define your own nothing though and throw it as much as possible. In ruby, if you do not explicitly return something, the last evaluated expression is returned.
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 simulate Nothing with exceptions.
class NothingError < RuntimeError
end
def nothing
raise NothingError
end
def foo x
if x>0 then x else nothing end
end
def nothingness
begin
yield
rescue NothingError
end
end
a = [1,2,3]
nothingness { a << foo(4) }
nothingness { a << foo(0) }
Probably not a great idea however ...
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.)
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.