當前位置: 首頁>>代碼示例 >>用法及示例精選 >>正文


Ruby Hash.insert()用法及代碼示例


Hash.insert() 方法

在本文中,我們將研究 Hash.insert() 方法。你們一定認為該方法必須做一些與插入某些元素有關的事情。它並不像看起來那麽簡單。好吧,我們將在其餘內容中解決這個問題。我們將嘗試借助語法和演示程序代碼來理解它。

方法說明:

此方法是 Ruby 庫中專門為 Array 類定義的 Public 實例方法的示例之一。此方法的用法方式是在具有給定索引的元素之前插入對象。如果您提供負索引,那麽它將從 Array 實例的後麵開始計算索引。此方法是破壞性方法的示例之一,其中這些方法所做的更改是永久性的。此方法沒有非破壞性版本。

用法:

    Array_instance.insert(index,object)

所需參數:

此方法接受兩個參數。第一個是您想要插入任何類的對象的索引,第二個詞是具有對象名稱的字符串。這兩個參數是強製性的,因為缺少它們會使您看到異常。參數的數量也可以更多,但絕不能少於 2。

範例1:

=begin
  Ruby program to demonstrate insert method
=end	

lang = ["C++","Java","Python","Ruby","Perl"]

puts "Array insert implementation."

puts "Enter the index where you want to insert:"
ind = gets.chomp.to_i

puts "Enter the object which you want to insert:"
ele = gets.chomp

if(ind = lang.insert(ind,ele))
	puts "Object inserted properly"
else
	puts "Error in inserting object"
end

puts "Array elements are:"
print lang

輸出

Array insert implementation.
Enter the index where you want to insert:
 2
Enter the object which you want to insert:
 HTML
Object inserted properly
Array elements are:
["C++", "Java", "HTML", "Python", "Ruby", "Perl"]

說明:

在上麵的代碼中,您可以觀察到我們向用戶詢問了她想要插入對象的索引和對象的名稱。在打印整個 Array 對象的輸出的最後一部分中,您可以觀察到我們僅在該索引處有 "HTML"。

範例2:

=begin
  Ruby program to demonstrate insert method
=end	

lang = ["C++","Java","Python","Ruby","Perl"]

puts "Array insert implementation."

puts "Enter the  first index where you want to insert:"
ind1 = gets.chomp.to_i

puts "Enter the first object which you want to insert:"
ele1 = gets.chomp

puts "Enter the  second object where you want to insert:"
ele2 = gets.chomp

puts "Enter the third object which you want to insert:"
ele3 = gets.chomp

if(ind = lang.insert(ind1,ele1,ele2,ele3))
	puts "Object inserted properly"
else
	puts "Error in inserting object"
end

puts "Array elements are:"
print lang

輸出

Array insert implementation.
Enter the  first index where you want to insert:
 2
Enter the first object which you want to insert:
 Java
Enter the  second object where you want to insert:
 Javascript
Enter the third object which you want to insert:
 COBOL
Object inserted properly
Array elements are:
["C++", "Java", "Java", "Javascript", "COBOL", "Python", "Ruby", "Perl"]

說明:

在上麵的代碼中,可以看到我們在Array實例中同時插入了幾個元素。我們已經向用戶詢問了她想從哪裏開始插入對象的索引。第一個對象插入該位置,其他對象插入連續位置。



相關用法


注:本文由純淨天空篩選整理自 Hash.insert() Method with Example in Ruby。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。