Created
March 24, 2012 21:20
-
-
Save afcapel/2188183 to your computer and use it in GitHub Desktop.
def behaviour
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# In Ruby you can use def anywhere in your code, but its behavior | |
# depends on the context in which it is used. | |
# Outside a class definition def creates singleton methods | |
foo = Object.new | |
# This will create a singleton method in FOO | |
def foo.speak | |
puts "foo" | |
end | |
foo.instance_eval do | |
def scream | |
puts "FOOOO!" | |
end | |
end | |
puts "Foo singleton methods: #{foo.singleton_methods.join(", ")}" | |
foo.speak | |
foo.scream | |
# Inside a class definition, def creates instance methods | |
class Bar | |
def speak | |
puts "bar" | |
end | |
def define_scream | |
def scream | |
puts "BAAAAAR!" | |
end | |
end | |
# Except in these cases | |
def self.whisper | |
puts "sssshhhh bar" | |
end | |
class << self | |
def shut_up | |
puts "..." | |
end | |
end | |
end | |
bar = Bar.new | |
bar.define_scream | |
puts "Bar singleton methods: #{Bar.singleton_methods.join(", ")}" | |
puts "Bar instance methods: #{Bar.instance_methods.grep(/speak|scream/).join(", ")}" | |
bar.speak | |
bar.scream | |
Bar.whisper | |
Bar.shut_up |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment