Nils and method chaining

后端 未结 9 2447
忘了有多久
忘了有多久 2021-02-14 19:21

I\'m just breaking into the ruby world and I could use a helping hand.

Suppose b is nil.

I\'d like the following code to return n

9条回答
  •  庸人自扰
    2021-02-14 19:40

    Remark in advance: b is a method, not a variable. So b 'is' not nil, it returns nil.

    When 'b' is a method, why not modify b, so it returns something, what can handle nil.

    See below for an example.


    You may define the missing methods:

    class A
      def b
        nil
      end
    end
    class NilClass
      def c(p);nil;end
      def e;nil;end
    end
    a = A.new
    
    a.b.c("d").e
    

    But I think, a rescue may fit your need better:

    class A
      def b
        nil
      end
    end
    a = A.new
    x = begin a.c.c("d").e 
    rescue NoMethodError
      nil
    end
    

    An example, how you may define a nil-like example.

    class A
      def b
        MyNil.new
      end
    end
    
    class MyNil
      def method_missing(m, *args, &block)
          if nil.respond_to?(m)
            nil.send(m)
        else
          self
        end
      end
      #Simulate nils bahaviour.
      def nil?;true;end
      def inspect;nil.inspect;end
      def to_s;nil;end
    end
    
    a = A.new
    x = a.b.c("d").e 
    p x
    puts x
    p x.nil?
    

提交回复
热议问题