Create an account

Very important

  • To access the important data of the forums, you must be active in each forum and especially in the leaks and database leaks section, send data and after sending the data and activity, data and important content will be opened and visible for you.
  • You will only see chat messages from people who are at or below your level.
  • More than 500,000 database leaks and millions of account leaks are waiting for you, so access and view with more activity.
  • Many important data are inactive and inaccessible for you, so open them with activity. (This will be done automatically)


Thread Rating:
  • 943 Vote(s) - 3.48 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Can Ruby return nothing?

#1
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)
Reply

#2
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 ...
Reply

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

#4
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.
Reply

#5
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.)
Reply

#6
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.
Reply

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



Forum Jump:


Users browsing this thread:
1 Guest(s)

©0Day  2016 - 2023 | All Rights Reserved.  Made with    for the community. Connected through