Skip to content

Instantly share code, notes, and snippets.

@mark
Forked from zobar/def.shard.rb
Last active August 31, 2015 12:24
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mark/11a68288a57379caebe4 to your computer and use it in GitHub Desktop.
Save mark/11a68288a57379caebe4 to your computer and use it in GitHub Desktop.
Nested function definitions are a bad idea in Ruby.
#!/usr/bin/env ruby -w
def defit
def ohai
puts "hello from #{self.class.inspect} #{self.inspect}"
end
puts "called defit in #{self.class.inspect} #{self.inspect}"
end
module MyModule
defit
end
:whatever.ohai
#!/usr/bin/env ruby -w
module YourModule
def self.defit
ohai = ->() { puts "hello from #{self.class.inspect} #{self.inspect}" }
puts "called defit in #{self.class.inspect} #{self.inspect}"
end
end
YourModule.defit
:whatever.ohai
#=> fails (yay!)
#!/usr/bin/env ruby -w
module YourModule
def self.defit
def ohai
puts "hello from #{self.class.inspect} #{self.inspect}"
end
puts "called defit in #{self.class.inspect} #{self.inspect}"
end
end
YourModule.defit
:whatever.ohai
#=> fails (yay)
#!/usr/bin/env ruby -w
def defit
def ohai
puts "hello from #{self.class.inspect} #{self.inspect}"
end
puts "called defit in #{self.class.inspect} #{self.inspect}"
end
# module MyModule
defit
# end
:whatever.ohai
#=> works (boo)
@zobar
Copy link

zobar commented Aug 31, 2015

inside_a_different_module is subtly wrong, too… it defines ohai as an instance method on YourModule rather than leaving it local to the body of defit

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment