在本文中,我们将研究Array.insert()方法。大家都必须认为该方法必须执行与插入某个元素有关的事情。它并不像看起来那么简单。好吧,我们将在其余内容中解决这个问题。我们将尝试借助语法并演示程序代码来理解它。
方法说明:
此方法是Public实例方法的示例之一,该方法在Ruby库中为Array类专门定义。此方法的工作方式是将对象插入具有给定索引的元素之前。如果提供负索引,则它将从Array实例的后面开始计算索引。此方法是破坏性方法的一个示例,其中这些方法所做的更改是永久性的。没有此方法的非破坏性版本。
语法:
Array_instance.insert(index,object)
Argument(s) 需要:
此方法接受两个参数。第一个是要在其中插入任何类的对象的索引,第二个是具有对象名称的String。这两个参数是强制性的,因为它们的缺失会使您看到Exception。参数的数量也可以更多,但不能少于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实例中同时插入了许多元素。我们已经要求用户提供从她想开始插入对象的位置开始的索引。第一个对象插入到该位置,其他对象插入到连续位置。