Skip to content

Instantly share code, notes, and snippets.

@nixterrimus
Created January 16, 2013 18:55
Show Gist options
  • Save nixterrimus/4549729 to your computer and use it in GitHub Desktop.
Save nixterrimus/4549729 to your computer and use it in GitHub Desktop.
Defining Methods on the top level main object in Ruby adds them as private methods to Object
# The semi-magic ability to define a method on the top level
# main object and have it be available as a private method to
# all object
# ref: http://stackoverflow.com/a/917842
def magical_mystery(thing)
"The Magical Mystery #{thing} is waiting to take you away"
end
class Rabbit
def to_s
magical_mystery("rabbit")
end
end
puts Rabbit.new
#-> The Magical Mystery rabbit is waiting to take you away
@parkr
Copy link

parkr commented Jan 22, 2013

Isn't this how it is in all cases? You define a method at the top level and it's available to everything in the tree, from top, down?

Also, you could always do this:

module Named
  def to_s
    "The Magical Mystery #{self.class.downcase} is waiting to take you away"
  end
end

class Rabbit
  extend Named
end

puts Rabbit.new

;-)

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