当前位置: 首页>>代码示例 >>用法及示例精选 >>正文


Ruby Array.insert()用法及代码示例


Array.insert() 方法

在本文中,我们将研究 Array.insert() 方法。你们一定认为该方法必须做一些与插入某个元素相关的事情。它并不像看起来那么简单。好吧,我们将在其余内容中解决这个问题。我们将尝试借助语法和演示程序代码来理解它。

方法说明:

此方法是 Ruby 库中专门为 Array 类定义的 Public 实例方法的示例之一。此方法的用法方式是在具有给定索引的元素之前插入对象。如果您提供负索引,那么它将从 Array 实例的后面开始计算索引。此方法是破坏性方法的一个示例,其中这些方法所做的更改是永久性的。此方法没有非破坏性版本。

用法:

    Array_instance.insert(index,object)

所需参数:

此方法接受两个参数。第一个是您想要插入任何类的对象的索引,第二个是具有对象名称的字符串。这两个参数是强制性的,因为缺少它们会使您看到异常。参数的数量也可以更多,但绝不能少于 2。

范例1:

=begin
  Ruby program to demonstrate insert method
=end	

# array declaration
Lang = ["C++","Java","Python","Ruby","Perl"]

puts "Array insert implementation."

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

# input the element to be inserted 
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	

# array declaration
Lang = ["C++","Java","Python","Ruby","Perl"]

puts "Array insert implementation."

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

# input the elements 
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 实例中同时插入了多个元素。我们已经向用户询问了她想从哪里开始插入对象的索引。第一个对象插入该位置,其他对象插入连续位置。



相关用法


注:本文由纯净天空筛选整理自 Array.insert() Method with Example in Ruby。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。