如何在 Ruby 中调用方法?


Ruby 中的方法,就像其他编程语言一样,将一个或多个可重复的语句捆绑到一个单元中。Ruby 中的方法名应该以小写字母开头。如果方法名以大写字母开头,Ruby 可能会认为它是一个常量,因此可能会错误地解析调用。

应该在调用方法之前定义方法,否则 Ruby 会因调用未定义的方法而引发异常。

在 Ruby 中,我们可以通过不同的方式**调用**方法。当我们在 Ruby 中调用方法时,括号的使用是可选的,因此可以省略。

在本文中,我们将探讨在 Ruby 中调用方法的不同方法。

调用没有参数的方法

在这个例子中,我正在调用一个**没有任何参数**的方法。请考虑下面显示的第一段代码。

示例

请考虑以下代码。

Open Compiler
string1 ='You can shake the world in a gentle way.' # "length" invoked on object puts string1

Explore our latest online courses and learn new skills at your own pace. Enroll and become a certified expert to boost your career.

输出

它将产生以下输出。

You can shake the world in a gentle way.

调用带有一个参数的方法

在这个例子中,我们正在调用一个接受**单个**参数的方法。请考虑下面显示的第二段代码。

示例

请考虑以下代码。

Open Compiler
# "sqrt" invoked on object # Math with one argument num = Math.sqrt(9) puts "Square Root of 9:" puts num

输出

它将产生以下输出。

Square Root of 9:
3.0

调用带有两个参数的方法

在这个例子中,我们正在调用一个接受**两个**参数的方法。请考虑下面显示的第三段代码。

示例

请考虑以下代码。

Open Compiler
def subtract(a, b) # 'subtract' method definition a - b end # Calling method 'subtract' c = subtract(20, 10) d = subtract(90, 45) puts c puts d

输出

它将产生以下输出。

10
45

调用类方法

在这个例子中,我们正在**调用**一个**类方法**。请考虑以下代码 -

示例

请考虑以下代码。

Open Compiler
# 'Vehicle' class definition class Vehicle # 'cat' function definition # having no arguments def function1 puts "The Bus is Moving at a Constant Speed." end end # Create a new instance of Animal obj = Vehicle.new # Instance method invocation obj.function1 # Class method call using send method obj.send :function1

输出

它将产生以下输出。

The Bus is Moving at a Constant Speed.
The Bus is Moving at a Constant Speed.

更新于: 2022年4月12日

591 次浏览

开启你的 职业生涯

通过完成课程获得认证

开始学习
广告