Ruby中带有示例的Array.index()方法

数组。index()方法

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

方法说明:

此方法是Public实例方法的示例之一,该方法在Ruby库中为Array类专门定义。此方法用于在作为参数传递的元素的帮助下找到Array实例中某个元素的索引。此方法以返回Array实例中第一个对象的索引的方式工作。如果提供的是块而不是参数,则该方法将返回该块返回布尔值“ True”的第一个对象的索引,如果找不到匹配项,则返回“ nil”。此方法是非破坏性方法的示例之一,其中通过这些方法所做的更改是永久性的。此方法没有破坏性版本。

语法:

    array_instance.index()
    or
    array_instance.index(|item| block)

Argument(s) 需要:

此方法接受Array实例中应该存在的参数。如果Array实例中不存在该元素,则此方法返回nil。

范例1:

=begin
  Ruby program to demonstrate index method
=end	

# 数组声明
lang = ["C++","Java","Python","Ruby","Perl"]

puts "Array index implementation."
puts "Enter the element whose index you want to find:"
ele = gets.chomp

if(ind = lang.index(ele))
	puts "#{ele} found at index #{ind}"
else
	puts "element is not a part of the Array instance"
end

输出结果

Array index implementation.
Enter the element whose index you want to find:
 Ruby
Ruby found at index 3

说明:

在上面的代码中,您可以观察到我们在向用户询问要查找其索引的元素。用户已经输入了对象“Ruby”,其是存在于3数组实例的索引。

范例2:

=begin
  Ruby program to demonstrate index method
=end	

# 数组声明
lang = ["C++","Java","Python","Ruby","Perl"]

puts "Array index implementation."
puts "Enter the element whose index you want to find:"
ele = gets.chomp

if(ind = lang.index{|ind| ind == ele})
	puts "#{ele} found at index #{ind}"
else
	puts "element is not a part of the Array instance"
end

输出结果

Array index implementation.
Enter the element whose index you want to find:
 Python
Python found at index 2

说明:

在上面的代码中,您可以看到我们正在方法内部传递一个块。该方法返回该块为True的第一个元素的索引。