Any way to determine which object called a method?

后端 未结 5 1827
悲哀的现实
悲哀的现实 2020-12-30 01:05

I\'m hoping that Ruby\'s message-passing infrastructure means there might be some clever trick for this.

How do I determine the calling object -- which object called

5条回答
  •  孤独总比滥情好
    2020-12-30 01:20

    Technology at its finest:

     1  # phone.rb
     2  class Phone
     3    def caller_id
     4      caller
     5    end
     6  end
     7  
     8  class RecklessDriver
     9    def initialize
    10      @phone = Phone.new
    11    end
    12    def dial
    13      @phone.caller_id
    14    end
    15  end
    16  
    17  p = Phone.new
    18  p.caller_id.inspect   # => ["phone.rb:18:in `
    '"] 19 20 macek = RecklessDriver.new 22 macek.dial.inspect # => ["phone.rb:13:in `dial'", "phone.rb:22:in `
    '"]

    Note: Line number for demonstrative purposes. phone.rb:X refers to Line X of the script.

    Look at phone.rb:13! This dial method is what sent the call! And phone.rb:22 refers to the reckless driver that used the dial method!

提交回复
热议问题