Ruby/Method/remove method
Материал из Wiki.crossplatform.ru
(Различия между версиями)
ViGOur (Обсуждение | вклад) м (1 версия: Импорт выборки материалов по Ruby) |
Текущая версия на 17:55, 13 сентября 2010
Remove a method for an intance
my_array = Array.new def my_array.random_dump(number) number.times { self << rand(100) } end p my_array.random_dump(3) p my_array.random_dump(2) p my_array # => [6, 45, 12, 49, 66] # That"s enough of that. class << my_array remove_method(:random_dump) end my_array.random_dump(4) # NoMethodError: undefined method "random_dump" for [6, 45, 12, 49, 66]:Array
Remove a new added method after calling
class OneTimeContainer def initialize(value) @use_just_once_then_destroy = value end def get_value remove_instance_variable(:@use_just_once_then_destroy) end end object_1 = OneTimeContainer.new(6) object_1.get_value # => 6 object_1.get_value # NameError: instance variable @use_just_once_then_destroy not defined object_2 = OneTimeContainer.new("ephemeron") object_2.get_value # => "ephemeron"
Undefining a Method
class RandomizingArray < Array def <<(e) insert(rand(size), e) end def [](i) super(rand(size)) end end a = RandomizingArray.new a << 1 << 2 << 3 << 4 << 5 << 6 # => [6, 3, 4, 5, 2, 1] p a[0] p a[0] p a[0] p class RandomizingArray remove_method("[]") end a[0] # => 6 a[0] # => 6 a[0] # => 6