Ulysse BN
Ulysse BN

Reputation: 11386

how to get class from which a method has been defined in ruby?

Having the snippet below:

class Foo
  def initialize
    puts self.class
  end
end

class Bar < Foo
  def bark
    puts self.class
  end
end

class Fizz < Bar
end

Fizz.new.bark

This snippet will output two times Fizz (live example). I would like to find something to replace self.class which allows this program to output Foo (from initialize) and then Bar (from bark).

My current solution is to hardcode function name, but I'd like something more dynamic.

Upvotes: 0

Views: 47

Answers (1)

Sergio Tulentsev
Sergio Tulentsev

Reputation: 230286

This works. (There's probably a better way, though.)

class Foo
  def initialize
    puts method(__callee__).owner
  end
end

class Bar < Foo
  def bark
    puts method(__callee__).owner
  end
end

class Fizz < Bar
end

Fizz.new.bark
# >> Foo
# >> Bar

Upvotes: 4

Related Questions