Skip to content

Instantly share code, notes, and snippets.

@iwinux
Created April 28, 2011 21:28
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 iwinux/947384 to your computer and use it in GitHub Desktop.
Save iwinux/947384 to your computer and use it in GitHub Desktop.
class Test
class << self
def x
return "X"
end
end
def y
return "Y"
end
class_eval <<-END
def self.a
puts "#{self.class}.a"
puts "#{self.x}"
end
END
# Test.a => Class.a, 'X'
# add puts "#{self.y}" inside self.a => NoMethodError: undefined method `y' for Test:Class
# Test.new.a => undefined method `a' for #<Test:0x8cba20c>
instance_eval <<-END
def b
puts "#{self.class}.b"
puts "#{self.x}"
end
END
# Test.b => Class.b, 'X'
# add puts "#{self.y}" inside self.b => NoMethodError: undefined method `y' for Test:Class
# Test.new.b => undefined method `b' for #<Test:0x8ca2e40>
instance_eval do
define_method(:c) do
puts "#{self.class}.c"
puts "#{self.y}"
end
end
# Test.c => NoMethodError: undefined method `c' for Test:Class
# Test.new.c => Test.c, 'Y'
# add puts "#{self.x}" inside self.c, and call Test.new.c
# => NoMethodError: undefined method `x' for #<Test:0x9f34518>
class << self
define_method(:d) do
puts "#{self.class}.d"
puts "#{self.x}"
#puts "#{self.y}"
end
end
# Test.d => Class.d, 'X'
# add puts "#{self.y}" inside self.c, and call Test.c
# => NoMethodError: undefined method `y' for Test:Class
# Test.new.d => undefined method `d' for #<Test:0x8cdce4c>
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment