Skip to content

Instantly share code, notes, and snippets.

@yesezra
Created March 12, 2012 04:52
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 yesezra/2019882 to your computer and use it in GitHub Desktop.
Save yesezra/2019882 to your computer and use it in GitHub Desktop.
It shouldn't be this hard
module Hi
def self.included(base)
base.class_eval do #Enumerable
def hello
puts "hello"
end
end
end
end
module Enumerable
include Hi
end
[].hello # "hello"
@rajasharan
Copy link

hi, quick random question. what does the def :hello accomplish when used this way inside a do-block code?

@yesezra
Copy link
Author

yesezra commented Mar 12, 2012

By using base.class_eval, the hello method is being defined in the context of the module or class that includes the Hi module. In this example, this means that the hello method is available on all instances of classes that include Enumerable – like Array, Hash, etc. This, in effect, is the same thing as adding the hello method definition directly to Enumerable.

@rajasharan
Copy link

thanks, got it.

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