Cu1ture
Cu1ture

Reputation: 1283

What is the difference between object.method(a,b) and method(a,b) in Ruby

I am very new to programming and am trying to learn Ruby. I can't quite get my head around methods at the moment. I uderstand that:

Methods allow me to execute a chunk of code without having to rewrite it, such a method looks like:

example_method

Arguments allow me to pass values into the code within the method that go in the place of the placeholders defined in the method. This way I can execute a set of code with different inputs. Methods with arguments look like:

example_method( x , y )

But I am confused about what an instantiation of a method on an object is actually doing. For example:

object.example_method( x, y )

What does this mean? Why is the method attached to an object with the period notation? Do we do this so we can reference Instance / Class variables of the object within our method? Is there any other reason to do this?

For the example if:

def example_method(x , y)
  x * y
end

Will object.exaple_method(a , b) be the same as example_method(a , b) ?

Thanks for any help, sorry if I am not being clear.

Upvotes: 1

Views: 78

Answers (2)

Uri Agassi
Uri Agassi

Reputation: 37409

Ruby is an Object Oriented language. This means that objects not only have members (=state) but also methods (=behavior). When you are calling a method on an object (is which case the object is called the caller) the method that runs is the method which corresponds to this object's type behavior.

When you are calling a method with no caller, self is implicitly the caller. From irb, self is considered main, or global scope.

Example:

def my_method(a)
  "#{a} from main"
end

class A
  def my_method(a)
    "#{a} from A"
  end
end

class B
  def my_method(a)
    "#{a} from B"
  end
end

a = A.new
b = B.new

my_method(1)
# => "1 from main"
a.my_method(1)
# => "1 from A"
b.my_method(1)
# => "1 from B"

Upvotes: 2

j-dexx
j-dexx

Reputation: 10406

If I assume correctly what you're asking it's a class method vs an instance method

def Object
  def self.example_method(x, y)
    #this is a class method
    x * y
  end

  def example_method(x,y)
    #this is an instance method
    x * y
  end
end

So now we've defined them here's how we call them

#This called the class method
Object.example_method(3,3) => 9

#To call the instance method we have to have an instance
object = Object.new
object.example_method(3,3) => 9

Upvotes: 0

Related Questions