0Day Forums
Can Ruby return nothing? - Printable Version

+- 0Day Forums (https://zeroday.vip)
+-- Forum: Coding (https://zeroday.vip/Forum-Coding)
+--- Forum: Ruby (https://zeroday.vip/Forum-Ruby)
+--- Thread: Can Ruby return nothing? (/Thread-Can-Ruby-return-nothing)



Can Ruby return nothing? - rand812075 - 07-19-2023

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)


RE: Can Ruby return nothing? - asperges37 - 07-19-2023

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 ...


RE: Can Ruby return nothing? - moats828958 - 07-19-2023

No, you can't return nothing. In ruby you always return something (even if it's just `nil`) - no way around that.


RE: Can Ruby return nothing? - unfatherlike648358 - 07-19-2023

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.


RE: Can Ruby return nothing? - stoneehcchuwue - 07-19-2023

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.)


RE: Can Ruby return nothing? - wish412980 - 07-19-2023

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.


RE: Can Ruby return nothing? - hammons616 - 07-19-2023

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.