Can Ruby return nothing?

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

提交回复
热议问题