This page contains automated test results for code from O'Reilly's Ruby Cookbook. If this code looks interesting or useful, you might want to buy the whole book.
Undefining a Method | ||
---|---|---|
Code | Expected | Actual |
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] | [6, 3, 4, 5, 2, 1] |
a[0] |
1 | 1 |
a[0] |
2 | 2 |
a[0] |
5 | 5 |
#No, seriously, a[0]. a[0] |
4 | 4 |
#It's a madhouse! A madhouse! a[0] |
3 | 3 |
#That does it! class RandomizingArray remove_method('[]') end a[0] |
6 | 6 |
a[0] |
6 | 6 |
a[0] |
6 | 6 |
a << 7 |
[6, 3, 4, 7, 5, 2, 1] | [6, 3, 4, 7, 5, 2, 1] |
class RandomizingArray remove_method(:length) end |
NameError: method `length' not defined in RandomizingArray ... |
NameError: method `length' not defined in RandomizingArray from (irb):27:in `remove_method' from (irb):27 |
class RandomizingArray undef_method(:length) end RandomizingArray.new.length |
NoMethodError: undefined method `length' for []:RandomizingArray ... |
NoMethodError: undefined method `length' for []:RandomizingArray from (irb):32 |
Array.new.length |
0 | 0 |
my_array = Array.new def my_array.random_dump(number) number.times { self << rand(100) } end my_array.random_dump(3) my_array.random_dump(2) my_array |
[6, 45, 12, 49, 66] | [6, 45, 12, 49, 66] |
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 ... |
NoMethodError: undefined method `random_dump' for [6, 45, 12, 49, 66]:Array from (irb):44 |
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 | 6 |
object_1.get_value |
NameError: instance variable @use_just_once_then_destroy not defined ... |
NameError: instance variable @use_just_once_then_destroy not defined from (irb):50:in `remove_instance_variable' from (irb):50:in `get_value' from (irb):55 |
object_2 = OneTimeContainer.new('ephemeron') object_2.get_value |
"ephemeron" | "ephemeron" |
class MyClass remove_instance_variable(:@use_just_once_then_destroy) end |
NameError: instance variable @use_just_once_then_destroy not defined ... |
NameError: instance variable @use_just_once_then_destroy not defined from (irb):59:in `remove_instance_variable' from (irb):59 |