How do methods get called?
@hubertlepicki
BRUG
2015-02-17 18:00
What is a method?
Everything's an object
Some syntax
class A def foo()
end
end
a = A.new
a.foo()
a.call(:foo)
Methods are objects
a = class A def foo(); puts "foo"; end
end.new
method = a.method(:foo)
=> #<Method: A#foo>
method.call(:foo)
foo
=> nil
Inheritance
class B < A end
b = B.new
method = b.method(:foo)
=> #<Method: B(A)#foo>
NoMethodError
a.i_do_not_exist
NoMethodError: undefined method `i_do_not_exist' for #<A:0x00000000df4d00>
method_missing
class A def method_missing(n, *a, &b) puts "Called me: #{n}" end end a.sdfsdfsdf Called me: sdfsdfsdf
b.sdfsdf
Called me: sdfsdf
a.method(:sdfsdf)
NameError: undefined method `sdfsdf'
Methods lookup
B.ancestors => [B, A, Object, Kernel, BasicObject
Mixing in modules
module Z; def foo; end; end
module Y; def foo; end; end
class B < A
include Y
include Z
end
B.new.method(:foo)
=> #<Method: B(Z)>
B.ancestors
=> [B, Z, Y, A, Object, Kernel, BasicObject]
Singleton class
b = B.new
def b.foo
end
b.method(:foo)
=> #<Method: #<B:0x0000000193d658>.foo>
b.singleton_class.ancestors
B.ancestors
=> [B, Z, Y, A, Object, Kernel, BasicObject]
super
module Y; def foo; puts "foo"; end
module Z; def foo; super; end
b.foo
"foo"
Thanks!
How do methods get called?
By Hubert Łępicki
How do methods get called?
- 1,304