Skip to content

Instantly share code, notes, and snippets.

@mkurtikov
Last active September 19, 2016 16:42
Show Gist options
  • Save mkurtikov/0c6737bcdc4a6daa3beef8c722345ce1 to your computer and use it in GitHub Desktop.
Save mkurtikov/0c6737bcdc4a6daa3beef8c722345ce1 to your computer and use it in GitHub Desktop.
Ruby Metaprogramming
'hello'.hello_world # NoMethodError: undefined method `hello_world' for "hello":String
class String
def hello_world
p 'Hello ' + self
end
end
'hello'.hello_world # "Hello hello"
class String < Integer; end # TypeError: superclass mismatch for class String
class Fixnum
def +(arg)
self * arg
end
end
2 + 4 # 8
module OddNum
refine Fixnum do
def -(arg)
self * arg
end
end
def self.minus(arg1, arg2)
arg1 * arg2
end
end
OddNum.minus(3,4) # 12
3 - 4 # -1
class A
def a
p 'a'
end
private
def b(arg)
p arg
end
end
A.new.send :a # "a"
A.new.send :b, 'hello' # "hello"
class A
def self.create_new_method(name, &block)
define_method name, &block
end
end
A.create_new_method(:print_x_times) do |str, times|
p str * times
end
A.new.print_x_times('hello ', 3) # "hello hello hello "
class A
def a
p 'a_a'
end
def b
p 'b_a'
end
end
class B < A
def a
p 'b_a'
end
def b
p 'b_b'
end
end
B.send :undef_method, :a
B.new.a # NoMethodError: undefined method `a' for #<B:0x007fbce9183af0>
A.new.a # "a_a"
B.send :remove_method, :b
B.new.b # "b_a"
A = Class.new do
define_method :a do
p 'A a'
end
def b
p 'A b'
end
end
A.new.a # "A a"
A.new.b # "A b"
self.class.send :remove_const, :A
A.new # NameError: uninitialized constant A
class A
def method_missing (method_name, *args, &block)
name = method_name.to_s
if valid_missing_method_name? name
string_to_print = extract_print_string name
p string_to_print
else
super
end
end
def extract_print_string(name)
name.match(missing_method_regex)[1]
end
def valid_missing_method_name?(name)
name.to_s =~ missing_method_regex
end
def missing_method_regex
/^print_(\w+)$/
end
end
A.new.print_hello # "hello"
A.new.hello_print # NoMethodError: undefined method `hello_print' for #<A:0x007ff21a10f860>
class A
def a
p 'a'
end
alias :b :a
end
A.new.b # "a"
A.send :remove_method, :a
A.new.a # undefined method `a' for #<A:0x007f9d1992b900>
A.new.b # "a"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment