Ruby 中的 Array push()、pop() 和 clear() 函式


說到陣列,Ruby 中使用最廣泛的函式是 push()、pop()clear() 函式。當我們分別想要輸入、取出和清除陣列資料時,就會使用這些函式。在本文中,我們將逐個瞭解所有這些函式。

push() 函式

Ruby 中的 push 函式用於在陣列的末尾追加元素。該函式可以接受單個或多個物件作為引數。

可以將以下程式碼作為 push() 函式的參考。

示例 1

# push() function example in Ruby

# few arrays
first_arr = ["Letters", "a", "b"]
second_arr = ["Words", "tuts", "Tuts"]
third_arr = ["Cities", "Noida", "Bangalore"]

# push() function
res_a = first_arr.push("c","d")
res_b = second_arr.push("Tut", "TutorialsPoint")
res_c = third_arr.push("Delhi", "Bangkok")

# printing result of push function
puts "#{res_a}"
puts "#{res_b}"
puts "#{res_c}"

輸出

["Letters", "a", "b", "c", "d"]
["Words", "tuts", "Tuts", "Tut", "TutorialsPoint"]
["Cities", "Noida", "Bangalore", "Delhi", "Bangkok"]

pop() 函式

當我們要從陣列中移除元素時,就會使用 pop 函式。它採用一個整數作為引數,該整數表示我們要從陣列中刪除多少個元素。

可以將以下示例作為參考。

示例 2

# pop() function example in Ruby

# few arrays
first_arr = ["Letters", "a", "b"]
second_arr = ["Words", "tuts", "Tuts","Tut", "TutorialsPoint"]

# pop() function
res_a = first_arr.pop
res_b = second_arr.pop(1)
res_c = second_arr.pop(2)

# printing result of pop function
puts "#{res_a}"
puts "#{res_b}"
puts "#{res_c}"

輸出

b
["TutorialsPoint"]
["Tuts", "Tut"]

clear() 函式

clear 函式用於移除給定陣列的所有元素,並返回不包含任何元素的陣列。

示例 3

可以參考以下程式碼

# clear() function example in Ruby

# few arrays
first_arr = ["Letters", "a", "b", "c", "d"]
second_arr = ["Words", "tuts", "Tuts", "Tut", "TutorialsPoint"]
third_arr = ["Cities", "Noida", "Bangalore", "Delhi", "Bangkok"]

# clear() function
res_a = first_arr.clear
res_b = second_arr.clear
res_c = third_arr.clear
# printing result of clear function

puts "#{res_a}"
puts "#{res_b}"
puts "#{res_c}"

輸出

[]
[]
[]

更新時間:2022 年 1 月 25 日

950 次瀏覽

開啟您的職業生涯

完成課程即可獲得認證

開始
廣告
© . All rights reserved.