是什么(A,B)在Ruby中的object.method之间的差值(A,B)和方法 [英] What is the difference between object.method(a,b) and method(a,b) in Ruby
问题描述
我很新的编程,我试图去学习Ruby的。我不能完全得到我的头周围的那一刻方法。我uderstand是:
方法允许我执行code一大块,而无需重写,这样的方法是这样的:
example_method
参数允许我值传递到了走在方法定义的占位符的地方法中的code。这样我可以执行一组code具有不同的输入。带参数的方法如下:
example_method(X,Y)
但我感到困惑的是什么对象的方法的一个实例实际上是做什么。例如:
object.example_method(X,Y)
这是什么意思?为什么方法连接到与周期符号的对象?我们做这个,所以我们可以参考实例 / 类我们的方法中的对象变量?是否有任何其他理由这样做呢?
有关的例子,如果:
高清example_method(X,Y)
X * Y
结束
威尔 object.exaple_method(A,B)
是一样的 example_method(A,B)
<? / p>
感谢您的帮助,对不起,如果我没有说清楚。
Ruby是一种的面向对象的语言。这意味着对象不仅拥有成员(=状态),但也方法(=行为)。当你调用一个对象的方法(是对象被称为这种情况下的主叫的)运行方法是对应于此对象的类型行为的方法。
当您呼叫没有来电,自
隐式调用者的方法。从IRB,自
被认为是主
或全球范围。
例如:
DEF my_method(一)
#{A}从主
结束A级
高清my_method(一)
#{A}从一个
结束
结束B类
高清my_method(一)
#{A}由B的
结束
结束A = A.new
B = B.newmy_method(1)
#=&GT; 从1主
a.my_method(1)
#=&GT; 1从一个
b.my_method(1)
#=&GT; 1从B
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.
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"
这篇关于是什么(A,B)在Ruby中的object.method之间的差值(A,B)和方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!