Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can Ruby return nothing?

Tags:

ruby

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)

like image 966
fl00r Avatar asked Mar 10 '11 23:03

fl00r


People also ask

What does empty function return Ruby?

The empty?() is an inbuilt method in Ruby returns true if the set is empty or it returns false.

What does Ruby method return?

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.

How do you return a string in Ruby?

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 .

What is implicit return in Ruby?

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 .


4 Answers

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.

like image 62
Jörg W Mittag Avatar answered Sep 23 '22 02:09

Jörg W Mittag


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

like image 44
sepp2k Avatar answered Sep 22 '22 02:09

sepp2k


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.

like image 28
tilleryj Avatar answered Sep 26 '22 02:09

tilleryj


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

like image 28
Guilherme Bernal Avatar answered Sep 22 '22 02:09

Guilherme Bernal