Skip to content

Instantly share code, notes, and snippets.

@detournemint
Created February 14, 2014 01:58
Show Gist options
  • Save detournemint/8994520 to your computer and use it in GitHub Desktop.
Save detournemint/8994520 to your computer and use it in GitHub Desktop.
Solutions to Metaprogramming In Ruby
$results = []
$results << class A
def initialize
@a = 11
@@a = 22
a = 33
end
@a = 1
@@a = 2
a = 3
end
$results << A.instance_variable_get(:@a)
$results << A.class_variable_get(:@@a)
class B < A
def initialize
$results << super
end
end
A.new
$results << A.new.instance_variable_get(:@a)
$results << A.class_variable_get(:@@a)
B.new
puts $results.sort!
class I
def like arg
puts "%s %s %s" % [self.class, self.class.instance_methods(false), arg]
end
end
c, m, arg = gets.split # input 'I like metaprogramming.'
# write your code here to display 'I like metaprogramming.'
$old_stdout = $stdout
class StdOut
def puts(string)
["[", "]", ":"].each do |bad|
string.gsub!(bad, '')
end
$old_stdout.puts string.to_s
end
def write
end
end
$stdout = StdOut.new
Object.const_get(c).new.send(m,arg)
animal = 'dog'
# define singleton speak() method
def animal.speak
puts 'Dog says Woof!'
end
animal.speak #=> 'Dog says Woof!'
the_binding = class A
@@a = 1
@a = 2
a = 3
binding
end
p eval('[@@a, @a, a]', the_binding) # Replace '*****' to your code
MaskedString = Class.new(String)
MaskedString.class_eval do
define_method(:tr_vowel) do
tr 'aeiou', '*'
end
define_singleton_method(:tr_vowel) do |str|
str.tr 'aeiou', '*'
end
end
s = MaskedString.new('hello')
p s.tr_vowel
p MaskedString.tr_vowel('goodbye')
class Dog
MSGS = {:dance => 'is dancing', :poo => 'is a smelly doggy!', :laugh => 'finds this hilarious!'}
def initialize(name)
@name = name
end
def method_missing(method)
"#{@name.capitalize} doesn't know #{method}"
end
def can(name, &block)
if block.nil?
block = -> { "#{@name} #{MSGS[name]}" }
end
self.define_singleton_method(name, &block)
end
end
lassie = Dog.new('Lassie')
lassie.can(:dance)
lassie.can(:poo)
lassie.can(:sing) { "#{@name} can sing!"}
stimpy = Dog.new('Stimpy')
stimpy.can(:dance)
stimpy.can(:cry){"#{@name} cried AHHHH"}
fido = Dog.new('Fido')
fido.can(:poo)
p lassie.dance
p lassie.poo
p lassie.laugh
p lassie.sing
puts
p fido.dance
p fido.poo
p fido.laugh
puts
p stimpy.dance
p stimpy.poo
p stimpy.laugh
p stimpy.cry
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment