Skip to content

Instantly share code, notes, and snippets.

@carlqt
Created August 9, 2014 00:32
Show Gist options
  • Save carlqt/c22769df9c441994813e to your computer and use it in GitHub Desktop.
Save carlqt/c22769df9c441994813e to your computer and use it in GitHub Desktop.
Ruby global scoping
class Animal
def dog
"I'm a dog"
end
def cat
"I'm a cat"
end
def bird
"I'm a bird"
end
end
# I want something like this to happend:
animal = Animal.new() do
dog # => "I'm a dog"
cat # => "I'm a cat"
bird # => "I'm a bird"
end
@ejaypcanaria
Copy link

Add this to your animal class:

def initialize(&block)
  instance_eval(&block)
end

@ejaypcanaria
Copy link

What it basically does is, it will run that block on the instance you just created (Animal.new)

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