Ruby 中的 String reverse 與 reverse! 函式


在 Ruby 中,在我們需要顛倒字串內容時,有這兩個可用的函式。這兩個函式是 reversereverse!。雖然兩者都用於反轉字串,但它們之間的唯一區別在於 reverse 函式反轉字串然後生成一個新字串,而 reverse! 函式原地反轉一個字串。

reverse 函式

reverse 函式的語法如下所示

new_str = str.reverse

現在,讓我們首先看一個 Ruby 中 reverse 函式的示例。

考慮以下所示程式碼。

示例 1

# the reverse method in Ruby

str = "TutorialsPoint"

# reversing the string
puts str.reverse

# printing the string
puts "Ruby".reverse

another_str = "India is Beautiful"

# reversing the string
res = another_str.reverse

# printing res
puts res

輸出

tnioPslairotuT
ybuR
lufituaeB si aidnI

reverse! 函式

reverse! 函式的語法如下所示。

str.reverse

現在讓我們看一個 reverse! 函式的示例,該函式在我們想要原地顛倒字串時使用。

考慮以下所示程式碼

示例 2

# the reverse! method in Ruby
str = "TutorialsPoint"

# reversing the string
puts str.reverse!

# printing the string
puts "Ruby".reverse!

another_str = "India is Beautiful"

# reversing the string
another_str.reverse!

# printing another_str
puts another_str

輸出

tnioPslairotuT
ybuR
lufituaeB si aidnI

更新時間: 2022-01-25

404 次瀏覽

啟動您的職業生涯

透過完成課程獲得認證

開始
廣告