Can Ruby return nothing?

后端 未结 6 1271
没有蜡笔的小新
没有蜡笔的小新 2021-02-12 17:53

Can I return nothing in ruby?

Just for educational purpose

For example:

myarray = [1,2,3]
myarray << some_method

def some_method
         


        
相关标签:
6条回答
  • 2021-02-12 18:01

    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.

    0 讨论(0)
  • 2021-02-12 18:06

    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.

    0 讨论(0)
  • 2021-02-12 18:08

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

    0 讨论(0)
  • 2021-02-12 18:10

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

    0 讨论(0)
  • 2021-02-12 18:16

    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.

    0 讨论(0)
  • 2021-02-12 18:21

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

    0 讨论(0)
提交回复
热议问题