Ruby Object Model: method calling

Get Started. It's Free
or sign up with your email address
Rocket clouds
Ruby Object Model: method calling by Mind Map: Ruby Object Model: method calling

1. What happens when you call a method?

1.1. when you call a method, Ruby does two things

1.1.1. it finds the method method lookup

1.1.2. it executes the method with the receiver as self

2. Method Execution

2.1. Every line of Ruby code is executed inside an object:

2.1.1. the current object

2.1.2. self only one object at a time can take the role of self when you call a method, the receiver takes the role of self, and from that moment on... all instance variables are instance variables of self all methods called without an explicit receiver are called on self as soon as your code explicitly calls a method on some other object, that other object becomes self in a class or module definition, the role of self is taken by the class or module outside a class/module definition and outside a method, the role of self is taken by the top level context main it's the object you're in when you're at the tip level of the call stack current object quiz puts "current object is #{self}" class MyClass puts "current object is #{self}" def my_stunning_method puts "current object is #{self}" end end see also

3. spell: Kernel Method

3.1. class Object includes Kernel

3.1.1. so, Kernel gets into every object's ancestors chain and you can call the Kernel methods from anywhere e.g. puts

3.1.2. you can take advantage of this mechanism yourself if you add a method to Kernel, this Kernel Method will be available to all objects e.g. The RubyGems example

4. Method Lookup

4.1. to find a method, Ruby goes into the receivers's class, and from there it climbs the ancestors chain until it finds the method

4.1.1. aka "one step to the right, than up" rule

4.1.2. Class#ancestors method asks a class for its ancestors chain

4.1.3. ancestors chain also include modules! also known as "include classes" When you include a module in a class, Ruby creates an anonymous class that wraps the module and inserts the anonymous class in the chain, just above the including class itself exercise: a simple program to spot in which class/module a method is defined require 'test/unit' class KernelTest < Test::Unit::TestCase def test_lookup_method assert_equal(Kernel, "a string instance".where_is(:send)) assert_equal(Kernel, "a string instance".where_is("instance_variable_get")) assert_equal(String, "a string instance".where_is("to_s")) assert_equal(Integer, 12.where_is("ceil")) assert_equal(Numeric, 12.where_is("nonzero?")) assert_nil("ciao".where_is("unexisting_method")) end end