Can Ruby return nothing?

后端 未结 6 1451
没有蜡笔的小新
没有蜡笔的小新 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: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 ...

提交回复
热议问题