“Metode Hapus Ruby” Kode Jawaban

Metode Hapus Ruby

# How to delete instance methods

# define an empty class
class Foo; end

# show all instance methods of Foo defined directyl on it
p Foo.instance_methods(false) #=> []

# add the `bar` method
class Foo
  def bar
    puts "I'm Foo#bar!"
  end
end

p Foo.instance_methods(false) #=> [:bar]
Foo.new.bar #=> I'm Foo#bar!

# delete the method
Foo.undef_method(:bar)
p Foo.instance_methods(false) #=> []
Foo.new.bar #=> undefined method `bar' for #<Foo:0x0000000106c9ef80> (NoMethodError)
Mateusz Drewniak

Metode Hapus Ruby

# How to delete class/singleton methods

# define an empty class
class Foo; end

# show all class/singleton methods of Foo
p Foo.singleton_methods #=> []

# add the `bar` method
class Foo
  def self.bar
    puts "I'm Foo::bar!"
  end
end

p Foo.singleton_methods #=> [:bar]
Foo.bar #=> I'm Foo::bar!

# delete the method
Foo.singleton_class.undef_method(:bar)
p Foo.singleton_methods #=> []
Foo.bar #=> undefined method `bar' for Foo:Class (NoMethodError)
Mateusz Drewniak

Jawaban yang mirip dengan “Metode Hapus Ruby”

Pertanyaan yang mirip dengan “Metode Hapus Ruby”

Lebih banyak jawaban terkait untuk “Metode Hapus Ruby” di Ruby

Jelajahi jawaban kode populer menurut bahasa

Jelajahi bahasa kode lainnya