如何在 Ruby 中呼叫方法?


Ruby 中的方法,就像其他程式語言一樣,將一個或多個可重複的語句捆綁到一個單元中。Ruby 中的方法名應該以小寫字母開頭。如果方法名以大寫字母開頭,Ruby 可能會認為它是一個常量,因此可能會錯誤地解析呼叫。

應該在呼叫方法之前定義方法,否則 Ruby 會因呼叫未定義的方法而引發異常。

在 Ruby 中,我們可以透過不同的方式**呼叫**方法。當我們在 Ruby 中呼叫方法時,括號的使用是可選的,因此可以省略。

在本文中,我們將探討在 Ruby 中呼叫方法的不同方法。

呼叫沒有引數的方法

在這個例子中,我正在呼叫一個**沒有任何引數**的方法。請考慮下面顯示的第一段程式碼。

示例

請考慮以下程式碼。

string1 ='You can shake the world in a gentle way.'

# "length" invoked on object
puts string1

輸出

它將產生以下輸出。

You can shake the world in a gentle way.

呼叫帶有一個引數的方法

在這個例子中,我們正在呼叫一個接受**單個**引數的方法。請考慮下面顯示的第二段程式碼。

示例

請考慮以下程式碼。

# "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

呼叫帶有兩個引數的方法

在這個例子中,我們正在呼叫一個接受**兩個**引數的方法。請考慮下面顯示的第三段程式碼。

示例

請考慮以下程式碼。

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

呼叫類方法

在這個例子中,我們正在**呼叫**一個**類方法**。請考慮以下程式碼 -

示例

請考慮以下程式碼。

# '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 次瀏覽

開啟你的 職業生涯

透過完成課程獲得認證

開始學習
廣告

© . All rights reserved.