Ruby: def def
Sometimes some Ruby programmers that want to give me a heart attack write code like this:
class Thing
def run
def loop_thing(i)
puts i
end
10.times { loop_thing(i) }
end
end
That’s a really cool nested function you made there! Only one problem before you go — RUBY DOESN’T HAVE NESTED FUNCTIONS.
thing = Thing.new
thing.run # 0..9
thing.loop_thing(31337) # 31337, no <NameError>
As we see here — in addition to being able to use define_method
, you
can actually run def
inside of a method body.
Now, cover your eyes if you don’t want to see the scary thing
class Array
def stop_the_mapping!
def map
raise 'But you told me to stop ;('
end
end
end
arr = [1, 2, 3]
arr.map { |x| x + 1 } # [2, 3, 4]
arr.stop_the_mapping!
arr.map { |x| x + 1 } # <RuntimeError>