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

Array.slice!()方法

在本文中,我们将研究Array.slice!()方法。大家都必须认为该方法必须执行与Array实例中的元素或对象切片有关的操作。它并不像看起来那么简单。好吧,我们将在其余内容中解决这个问题。我们将尝试借助语法并演示程序代码来理解它。

方法说明:

该方法是一个公共实例方法,为Ruby库中的Array类定义。此方法对元素引用起作用,并在与方法调用一起传递的索引处返回元素。如果通过方法传递两个参数,并且这些参数分别是开始和长度,则该方法将返回一个子数组,该子数组将包含从开始索引到长度索引的元素。在方法调用时将范围作为参数传递的情况下,此方法将返回子数组。此方法是破坏性方法的示例之一,在该方法中,该方法使自身Array中的对象的实际排列发生更改。

语法:

    array_instance.slice!(index) -> object or nil
    or
    array_instance.slice!(start,length)-> new_array or nil
    or
    array_instance.slice!(range)-> new_array or nil

Argument(s) 需要:

您可以在调用方法时在此方法内提供单个索引或范围,起始和长度作为参数。您将根据在方法内部传递的参数获得输出。

范例1:

=begin
  Ruby program to demonstrate slice! method
=end

# 数组声明
table = [2,4,6,8,10,12,14,16,18,20]

puts "Array slice! implementation"

puts "Enter the index you want to slice"
ind = gets.chomp.to_i

if(table.slice!(ind))
	puts "The element which is sliced is #{table.slice!(ind)}"
else
	puts "Array index out of bound"
end

puts "Array instance after slicing: #{table}"

输出结果

Array slice! implementation
Enter the index you want to slice
 4
The element which is sliced is 12
Array instance after slicing: [2, 4, 6, 8, 14, 16, 18, 20]

说明:

在上面的代码中,您可以观察到我们正在借助Array.slice!()方法从Array实例切片元素。我们将在要求用户输入输入值的索引的帮助下对其进行切片。第四索引对象已从Array实例中切出。由于该方法是破坏性方法的示例之一,因此该方法使self Array发生了变化。

范例2:

=begin
  Ruby program to demonstrate slice! method
=end

# 数组声明
table = [2,4,6,8,10,12,14,16,18,20]

puts "Array slice! implementation"

puts "Enter the start index you want to slice"
ind = gets.chomp.to_i

puts "Enter the length"
len = gets.chomp.to_i

if(table.slice(ind,len))
	puts "The sub array which is sliced is #{table.slice!(ind,len)}"
else
	puts "Array index out of bound"
end

puts "Array instance after slicing: #{table}"

输出结果

Array slice! implementation
Enter the start index you want to slice
 3
Enter the length
 5
The sub array which is sliced is [8, 10, 12, 14, 16]
Array instance after slicing: [2, 4, 6, 18, 20]

说明:

在上面的代码中,您可以观察到,借助于Array.slice!()方法,我们正在根据Array实例的元素创建一个子数组。我们在两个参数的帮助下对其进行切片,即开始索引和要求用户输入值的长度。在输出中,你可以看到,Array实例已经从3切片第三索引和到7得到的在含有五个对象的数组的形成指数。由于该方法是破坏性方法的示例之一,因此该方法给self Array带来了变化。

范例3:

=begin
  Ruby program to demonstrate slice! method
=end

# 数组声明
table = [2,4,6,8,10,12,14,16,18,20]

puts "Array slice! implementation"

puts "Enter the start index you want to slice"
ind = gets.chomp.to_i

puts "Enter the end index you want to slice"
len = gets.chomp.to_i

if(table.slice(ind..len))
	puts "The sub array which is sliced is #{table.slice!(ind..len)}"
else
	puts "Array index out of bound"
end

puts "Array instance after slicing: #{table}"

输出结果

Array slice! implementation
Enter the start index you want to slice
 3
Enter the end index you want to slice
 5
The sub array which is sliced is [8, 10, 12]
Array instance after slicing: [2, 4, 6, 14, 16, 18, 20]

说明:

在上面的代码中,您可以观察到我们正在从Array实例中切片一个子数组。我们在要求用户输入值的范围内对其进行切片。在输出中,你可以看到,Array实例已经从3切片第三索引和到5得到的,其中包含三个对象的数组的形成指数。由于该方法是破坏性方法的示例之一,因此该方法使self Array发生了变化。