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

人走茶凉 提交于 2020-01-05 12:23:25

问题


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.


回答1:


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"



回答2:


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


来源:https://stackoverflow.com/questions/24915354/what-is-the-difference-between-object-methoda-b-and-methoda-b-in-ruby

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!