如何在Ruby中使用数组方法

介绍 (Introduction)

Arrays let you represent lists of data in your programs. Once you have data in an array, you can sort it, remove duplicates, reverse its order, extract sections of the array, or search through arrays for specific data. You can also convert an array to a string, transform one array of data into another, and roll up an array into a single value.

数组使您可以表示程序中的数据列表。 数组中有数据后,就可以对其进行排序,删除重复项,颠倒其顺序,提取数组的各个部分或在数组中搜索特定数据。 您还可以将数组转换为字符串 ,将一个数据数组转换为另一个数组,并将一个数组汇总为单个值。

In this tutorial, you’ll explore some of the most practical methods Ruby provide for working with data stored in arrays.

在本教程中,您将探索Ruby提供的一些最实用的方法来处理存储在数组中的数据。

As you work through this tutorial, you’ll see some methods that end with an exclamation point (!). These methods often have side-effects, such as mutating the original value, or raising exceptions. Many methods you’ll use in this tutorial have a related method with this suffix.

在学习本教程时,您会看到一些以感叹号( ! )结尾的方法。 这些方法通常会产生副作用,例如变异原始值或引发异常。 您将在本教程中使用的许多方法都有与此后缀相关的方法。

You’ll also come across methods that end with a question mark (?). These methods return a boolean value.

您还将遇到以问号( ? )结尾的方法。 这些方法返回一个布尔值。

These are a naming convention used throughout Ruby. It’s not something that’s enforced at the program level; it’s just another way to identify what you can expect from the method.

这些是整个Ruby中使用的命名约定。 它不是在程序级别强制执行的; 这是识别您可以从该方法中得到什么的另一种方法。

Let’s start our exploration of array methods by looking at several ways to access elements

让我们开始研究数组方法,方法是查看访问元素的几种方法

访问元素 (Accessing Elements)

If you’ve already followed the tutorial How To Work with Arrays in Ruby, you know you can access an individual element using its index, which is zero-based, like this:

如果您已经按照教程“ 如何在Ruby中使用数组”进行了学习 ,则知道可以使用基于元素的索引(从零开始)访问单个元素,如下所示:

sharks = ["Tiger", "Great White", "Hammerhead", "Angel"]
sharks[0]    # "Tiger"
sharks[1]    # "Great White"
sharks[-1]   # "Angel"

You also might recall that you can use the first and last methods to grab the first and last elements of an array:

您可能还记得,可以使用firstlast方法来获取数组的first和last元素:

sharks = ["Tiger", "Great White", "Hammerhead", "Angel"]
sharks.first   # "Tiger"
sharks.last    # "Angel"

Finally, when you access an element that doesn’t exist, you will get nil. But if you’d like to get an error instead, use the fetch method:

最后,当您访问不存在的元素时,将得到nil 。 但是,如果您想得到一个错误,请使用fetch方法:

sharks.fetch(42)

   
   
Output
IndexError: index 42 outside of array bounds: -4...4

If you’d rather specify your own default instead of raising an error, you can do that too:

如果您希望指定自己的默认值而不是引发错误,也可以这样做:

sharks.fetch(42, "Nope")     # "Nope"

Now let’s look at how to get more than one element from an array.

现在让我们看一下如何从数组中获取多个元素。

检索多个元素 (Retrieving Multiple Elements)

There are times you might want to grab a subset of values from your array instead of just a single element.

有时您可能想从数组中获取值的子集,而不仅仅是单个元素。

If you specify a starting index, followed by the number of elements you want, you’ll get a new array containing those values. For example, you can grab the two middle entries from the sharks array like this:

如果指定起始索引,然后指定所需的元素数,则会得到一个包含这些值的新数组。 例如,您可以像下面这样从sharks数组中获取两个中间条目:

sharks = ["Tiger", "Great White", "Hammerhead", "Angel"]
sharks[1,2]   # ["Great White", "Hammerhead"]

We start at index 1, which is "Great White", and we specify we want 2 elements, so we get a new array containing "Great White" and "Hammerhead".

我们从索引1开始,即"Great White" ,并指定需要2元素,因此得到一个包含"Great White""Hammerhead"的新数组。

You can use the slice method to do the same thing:

您可以使用slice方法执行相同的操作:

sharks = ["Tiger", "Great White", "Hammerhead", "Angel"]
sharks.slice(1,2)   # ["Great White", "Hammerhead"]

The slice method also returns a new array, leaving the original array unaltered. However, if you use the slice! method, the original array will be changed as well.

slice方法还返回一个新数组,保留原始数组不变。 但是,如果您使用slice! 方法,原始数组也将更改。

The take method lets you grab the specified number of entries from the beginning of an array:

take方法使您可以从数组的开头抓取指定数量的条目:

sharks = ["Tiger", "Great White", "Hammerhead", "Angel"]
sharks.take(2)  # ["Tiger", "Great White"]

Sometimes you want to grab a random value from an array instead of a specific one. Let’s explore how.

有时您想从数组中获取随机值,而不是特定值。 让我们探讨一下。

从数组中获取随机条目 (Getting a Random Entry from an Array)

You might be working on a game of chance, or maybe you’re writing a program that picks a contest winner. Those kinds of things require some kind of random value. A common solution is to put the possible choices in an array and select a random index.

您可能正在玩机会游戏,或者正在编写一个程序来挑选比赛获胜者。 这些事情需要某种随机值。 常见的解决方案是将可能的选择放入数组中,然后选择一个随机索引。

To get a random element from an array, you could generate a random index between 0 and the last index of the array and use that as an index to retrieve the value, but there’s an easier way: thesample method grabs a random entry from an array.

要从数组中获取随机元素,您可以在0和数组的最后一个索引之间生成一个随机索引,并使用该索引作为索引来检索值,但是有一种更简单的方法: sample方法从数组。

Let’s use it to grab a random answer from an array of stock answers, creating a primitive version of a Magic 8-Ball game:

让我们用它来从一系列的答案中随机抽取答案,从而创建了Magic 8-Ball游戏的原始版本:

8ball.rb
8ball.rb
answers = ["Yes", "No", "Maybe", "Ask again later"]
print answers.sample

   
   
Output
Maybe

The sample method also accepts an argument that returns an array of random entries, so if you happen to need more than one random entry, just supply the number you’d like:

sample方法还接受一个返回随机条目数组的参数,因此,如果您碰巧需要多个随机条目,只需提供所需的数字即可:

random_sharks.rb
random_sharks.rb
sharks = ["Hammerhead", "Great White", "Tiger", "Whale"]
sample = sharks.sample(2)
print sample

   
   
Output
["Whale", "Great White"]

Let’s look at how to find specific elements in an array next.

接下来让我们看看如何在数组中查找特定元素。

查找和过滤元素 (Finding and Filtering Elements)

When you’re looking for specific elements in an array, you typically iterate over its elements until you find what you’re looking for. But Ruby arrays provide several methods specifically designed to simplify the process of searching through arrays.

在数组中查找特定元素时,通常会遍历其元素,直到找到所需的内容。 但是Ruby数组提供了几种专门设计用于简化数组搜索过程的方法。

If you just want to see if an element exists, you can use the include? method, which returns true if the specified data is an element of the array:

如果只想查看元素是否存在,可以使用include? 方法,如果指定的数据是数组的元素,则返回true

sharks = ["Hammerhead", "Great White", "Tiger", "Whale"]
sharks.include? "Tiger"      # true

["a", "b", "c"].include? 2   # false

However, include? requires an exact match, so you can’t look for a partial word.

但是, include? 需要完全匹配,因此您无法查找部分单词。

sharks = ["Hammerhead", "Great White", "Tiger", "Whale"]
sharks.include? "Tiger"      # true
sharks.include? "tiger"      # false
sharks.include? "ti"         # false

The find method locates and returns the first element in the array that matches a condition you specify.

find方法查找并返回数组中与您指定的条件匹配的第一个元素。

For example, to identify the first entry in the sharks array that contains the letter a, you could use the each method to compare each entry and stop iterating when you find the first one, like this:

例如,要标识包含字母asharks数组中的第一个条目,可以使用each方法比较每个条目并在找到第一个条目时停止迭代,如下所示:

sharks = ["Hammerhead", "Great White", "Tiger", "Whale"]
result = nil
sharks.each do |shark|
  if sharks.include? "a"
    result = shark
    break
  end
end

Or you could use the find method to do the same thing:

或者,您可以使用find方法执行相同的操作:

sharks = ["Hammerhead", "Great White", "Tiger", "Whale"]
result = sharks.find {|item| item.include?("a")}
print result

   
   
Output
Hammerhead

find executes the block you provide for each element in the array. If the last expression in the block evaluates to true, the find method returns the value and stops iterating. If it doesn’t find anything after iterating through all of the elements, it returns nil.

find执行为数组中每个元素提供的块。 如果该块中的最后一个表达式的值为true ,则find方法返回该值并停止迭代。 如果遍历所有元素后没有找到任何内容,则返回nil

The select method works in a similar way, but it constructs a new array containing all of the elements that match the condition, instead of just returning a single value and stopping.

select方法的工作方式类似,但是它构造了一个包含所有与条件匹配的元素的新数组,而不仅仅是返回单个值并停止。

sharks = ["Hammerhead", "Great White", "Tiger", "Whale"]
results = sharks.select {|item| item.include?("a")}
print results

   
   
Output
["Hammerhead", "Great White", "Whale"]

The reject method returns a new array containing elements that don’t match the condition. You can think of it as a filter that removes elements you don’t want. Here’s an example that rejects all entries that contain the letter a:

reject方法返回一个新数组,其中包含与条件匹配的元素。 您可以将其视为可以删除不需要的元素的过滤器。 这是一个拒绝包含字母a所有条目的示例:

sharks = ["Hammerhead", "Great White", "Tiger", "Whale"]
results = sharks.reject {|item| item.include?("a")}
print results

   
   
Output
["Tiger"]

select and reject both return a new array, leaving the original array unchanged. However, if you use the select! and reject! methods, the original array will be modified.

selectreject都返回一个新数组,而原始数组保持不变。 但是,如果使用select! reject! 方法,原始数组将被修改。

The find_all method is an alias for select, but there is no find_all! method.

find_all方法是select的别名,但是没有find_all! 方法。

Next, let’s look at how to sort the values of an array.

接下来,让我们看看如何对数组的值进行排序。

数组排序 (Sorting an Array)

Sorting data is a common practice. You may need to alphabetize a list of names or sort numbers from smallest to largest.

排序数据是一种常见的做法。 您可能需要按字母顺序排列名称列表或按从小到大的顺序对数字进行排序。

Ruby arrays have a reverse method which can reverse the order of the elements in an array. If you have a list of data that’s already organised, reverse is a quick way to flip the elements around:

Ruby数组具有一个reverse方法,该方法可以反转数组中元素的顺序。 如果您具有已组织的数据列表,则reverse是一种快速翻转元素的方法:

sharks = ["Angel", "Great White", "Hammerhead", "Tiger"]
reversed_sharks = sharks.reverse
print reversed_sharks

   
   
Output
["Tiger", "Hammerhead", "Great White", "Angel"]

The reverse method returns a new array and doesn’t modify the original. Use the reverse! method if you want to change the original array instead.

reverse方法返回一个新数组,并且不修改原始数组。 reverse!使用reverse! 方法,如果您想更改原始数组。

However, reversing an array isn’t always the most efficent, or practical, way to sort data. Use the sort method to sort the elements in an array the way you’d like.

但是,反转数组并非总是最有效或最实用的数据排序方法。 使用sort方法对数组中的元素进行排序。

For simple arrays of strings or numbers, the sort method is efficient and will give you the results you’re looking for:

对于简单的字符串或数字数组, sort方法是有效的,它将为您提供所需的结果:

sharks = ["Tiger", "Great White", "Hammerhead", "Angel"]
sorted_sharks = sharks.sort
print sorted_sharks

   
   
Output
["Angel", "Great White", "Hammerhead", "Tiger"]

However, if you wanted to sort things a different way, you’ll want to tell the sort method how to do that. The sort method takes a Ruby block that gives you access to elements in the array so you can compare them.

但是,如果您想以其他方式对事物进行排序,则需要告诉sort方法如何做到这一点。 sort方法采用一个Ruby块,该块使您可以访问数组中的元素,以便您可以比较它们。

To do the comparison, you use the comparison operator (<=>), often referred to as the spaceship operator. This operator compares two Ruby objects and returns -1 if the object on the left is smaller, 0 if the objects are the same, and 1 if the object on the left is bigger.

要进行比较,请使用比较运算符 ( <=> ),通常称为太空飞船运算符 。 这个操作符比较两个Ruby对象并返回-1如果左侧的对象较小, 0如果对象是相同的,和1如果左边的对象是更大的。

1 <=> 2    # -1
2 <=> 2    #  0
2 <=> 1    #  1

Ruby’s sort method accepts a block that must return -1, 0, or 1, which it then uses to sort the values in the array.

Ruby的sort方法接受块必须返回-10 ,或1 ,然后用它来在阵列中的值进行排序。

Here’s an example that explicitly compares the entries in the array to sort in ascending order:

这是一个示例,该示例显式比较数组中的条目以升序排序:

sharks = ["Tiger", "Great White", "Hammerhead", "Angel"]
sorted_sharks = sharks.sort{|a,b| a <=> b }
print sorted_sharks

The a and b variables represent individual elements in the array that are compared. The result looks like this:

ab变量表示要比较的数组中的各个元素。 结果看起来像这样:


   
   
Output
["Angel", "Great White", "Hammerhead", "Tiger"]

To sort the sharks in the reverse order, reverse the objects in the comparison:

要以相反的顺序对鲨鱼进行排序,请在比较中反转对象:

sharks = ["Tiger", "Great White", "Hammerhead", "Angel"]
sorted_sharks = sharks.sort{|a,b| b <=> a }
print sorted_sharks

   
   
Output
["Tiger", "Hammerhead", "Great White", "Angel"]

The sort method is great for arrays containing simple data types like integers, floats, and strings. But when arrays contain more complex objects, you’ll have to do a little more work.

对于包含简单数据类型(例如整数,浮点数和字符串)的数组, sort方法非常有用。 但是,当数组包含更复杂的对象时,您将不得不做更多的工作。

Here’s an array of hashes, with each hash representing a shark:

这是一个哈希数组,每个哈希代表一个鲨鱼:

sharks = [
  {name: "Hammerhead"},
  {name: "Great white"},
  {name: "Angel"}
]

Sorting this with sort isn’t as easy. Calling sort on the array fails:

sort不是那么容易。 在数组上调用sort失败:

sharks.sort

   
   
Output
ArgumentError: comparison of Hash with Hash failed

In order to do the comparison, we have to tell sort what we want to compare. So we’ll compare the values of the :name key in the hash:

为了进行比较,我们必须告诉sort我们要比较的内容。 因此,我们将在哈希中比较:name键的值:

sorted_sharks.sort{|a, b| a[:name] <=> b[:name]}
print sorted_sharks

   
   
Output
[{:name=>"Angel"}, {:name=>"Great white"}, {:name=>"Hammerhead"}]

When you’re working with more complex structures, you might want to look at the sort_by method instead, which uses a more efficient algorithm for sorting. sort_by takes a block that only requires one argument, the reference to the current element in the array:

当您使用更复杂的结构时,您可能想看一下sort_by方法,该方法使用一种更高效的算法进行排序。 sort_by采用一个只需要一个参数的块,即对数组中当前元素的引用:

sharks = [
  {name: "Hammerhead"},
  {name: "Great white"},
  {name: "Angel"}
]

sorted_sharks = sharks.sort_by{|shark| shark[:name] }
print sorted_sharks

   
   
Output
[{:name=>"Angel"}, {:name=>"Great white"}, {:name=>"Hammerhead"}]

The sort_by method implements a Schwartzian transform, a sorting algorithm best suited for comparing objects based on the value of a specific key. Therefore, you’ll find yourself using sort_by whenever comparing collections of objects, as it’s more efficient.

sort_by方法实现了Schwartzian变换 ,这是最适合根据特定键的值比较对象的排序算法。 因此,每当比较对象集合时,您都会发现使用sort_by可以提高效率。

Both sort and sort_by return new arrays, leaving the original array intact. If you want to modify the original array, use sort! and sort_by! instead.

sortsort_by返回新数组,保留原始数组不变。 如果要修改原始数组,请使用sort!sort_by! 代替。

In addition to sorting values, you might also want to get rid of duplicates.

除了对值进行排序之外,您可能还希望消除重复项。

删除重复元素 (Removing Duplicate Elements)

Sometimes you’ll get lists of data that have some duplication. You could iterate through the array and filter out the duplicates, but Ruby’s uniq method makes that a lot easier. The uniq method returns a new array with all duplicate values removed.

有时您会得到重复的数据列表。 您可以遍历数组并过滤出重复项,但是Ruby的uniq方法使操作变得容易uniquniq方法返回一个删除了所有重复值的新数组。

[1,2,3,4,1,5,3].uniq   # [1,2,3,4,5]

Sometimes, when you merge two sets of data, you’ll end up with duplicates. Take these two arrays of sharks:

有时,当您合并两组数据时,最终会出现重复项。 拿这两个鲨鱼阵列:

sharks = ["Tiger", "Great White"]
new_sharks = ["Tiger", "Hammerhead"]

If we add them together, we’ll get a duplicate entry:

如果将它们加在一起,将会得到重复的条目:

sharks + new_sharks
# ["Tiger", "Great White", "Tiger", "Hammerhead"]

You could use uniq to remove the duplicates, but it’s better to avoid introducing them entirely. Instead of adding the arrays together, use the pipe operator|, which merges the arrays together:

您可以使用uniq删除重复项,但是最好避免完全引入它们。 不用将数组加在一起,而是使用管道运算符| ,将数组合并在一起:

sharks | new_sharks
# ["Tiger", "Great White", "Hammerhead"]

Ruby arrays also support subtraction, which means you could subtract new_sharks from sharks to get only the new values:

Ruby阵列还支持减法,这意味着你可以减去new_sharkssharks只得到新的价值:

sharks = ["Tiger", "Great White"]
new_sharks = ["Tiger", "Hammerhead"]
sharks - new_sharks   # ["Great White"]

Next, let’s look at how to manipulate each element’s value.

接下来,让我们看一下如何操纵每个元素的值。

转换资料 (Transforming Data)

The map method, and its alias collect, can transform the contents of array, meaning that it can perform an operation on each element in the array.

map方法及其别名collect可以转换数组的内容,这意味着它可以对数组中的每个元素执行操作。

For example, you can use map to perform arithmetic on each entry in an array, and create a new array containing the new values:

例如,您可以使用map对数组中的每个条目执行算术运算,并创建一个包含新值的新数组:

numbers = [2,4,6,8]

# square each number
squared_numbers = numbers.map {|number| number * number}

print squared_numbers

The squared_numbers variable is an array of the original numbers, squared:

squared_numbers变量是原始数字的平方的数组:

[4, 16, 36, 64]

map is often used in web applications to transform an array into elements for an HTML dropdown list. Here’s a very simplified version of how that might look:

map在Web应用程序中通常用于将数组转换为HTML下拉列表的元素。 这是看起来的非常简化的版本:

sharks = ["Hammerhead", "Great White", "Tiger", "Whale"]

options = sharks.map {|shark| "<option>#{shark}</option>"}

print options

The options array now has each shark wrapped in the <option></option> HTML tag:

现在, options数组的每个鲨鱼都包裹在<option></option> HTML标记中:

["<option>Hammerhead</option>", "<option>Great White</option>", "<option>Tiger</option>", "<option>Whale</option>"]

map returns a new array, leaving the original array unmodified. Using map! would modify the existing array. And remember that map has an alias called collect. You should be consistent and use one or the other in your code.

map返回一个新数组,保留原始数组不变。 使用map! 将修改现有数组。 并记住, map有一个别名称为collect 。 您应该保持一致,并在代码中使用一个或另一个。

Since map returns a new array, the array can then be transformed and maniupated further, or even converted to a string. Let’s look at that next.

由于map返回一个新数组,因此可以对该数组进行转换和进一步处理,甚至将其转换为字符串。 接下来让我们看看。

将数组转换为字符串 (Converting an Array to a String)

All objects in Ruby have a to_s method, which converts the object to a string. This is what the print statement uses. Given our array of sharks:

Ruby中的所有对象都有一个to_s方法,该方法将对象转换为字符串。 这就是print语句所使用的。 考虑到我们的sharks

sharks = ["Hammerhead", "Great White", "Tiger", "Whale"]

Calling the to_s method creates this string:

调用to_s方法将创建以下字符串:

"[\"Hammerhead\", \"Great White\", \"Tiger\", \"Whale\"]"

That’s great for debugging, but it’s not very useful in a real program.

这对于调试非常有用,但是在实际程序中并不是很有用。

The join method converts an array to a string, but gives you much more control of how you want the elements combined. The join method takes an argument that specifies the character you want to use as a separator. To transform the array of sharks into a string of shark names separated by spaces, you’d do something like this:

join方法将数组转换为字符串,但使您可以更好地控制元素的组合方式。 join方法采用一个参数,该参数指定要用作分隔符的字符。 要将鲨鱼数组转换为由空格分隔的一串鲨鱼名称,您需要执行以下操作:

shark_join.rb
shark_join.rb
sharks = ["Hammerhead", "Great White", "Tiger", "Whale"]
result = sharks.join(" ")
print result

   
   
Output
Hammerhead Great White Tiger Whale

If you wanted each shark name separated by a comma and a space, use a comma and a space as your delimiter:

如果你想在每一鲨鱼名称由逗号空格分隔,用逗号和您的分隔符的空间:

shark_join.rb
shark_join.rb
sharks = ["Hammerhead", "Great White", "Tiger", "Whale"]
result = sharks.join(", ")
print result

   
   
Output
Hammerhead, Great White, Tiger, Whale

If you don’t specify an argument to the join method, you’ll still get a string, but it won’t have any delimiters:

如果不为join方法指定参数,您仍然会得到一个字符串,但是它没有任何定界符:

shark_join.rb
shark_join.rb
sharks = ["Hammerhead", "Great White", "Tiger", "Whale"]
result = sharks.join
print result

   
   
Output
HammerheadGreat WhiteTigerWhale

Using join in conjunction with map is a quick way to transform an array of data into output. Use map to transform each element in the data, then use join to transform the whole thing into a string you can print out. Remember our example of transforming our sharks array into an array of HTML elements? Here’s that same example again, but this time we’ll use join to convert the array of elements into a string with newline characters as the separator:

joinmap结合使用是将数据数组转换为输出的快速方法。 使用map转换数据中的每个元素,然后使用join将整个对象转换为可以打印的字符串。 还记得我们将sharks数组转换为HTML元素数组的示例吗? 这再次是同一示例,但是这次我们将使用join将元素数组转换为以换行符作为分隔符的字符串:

map.rb
map.rb
sharks = ["Hammerhead", "Great White", "Tiger", "Whale"]
options = sharks.map {|shark| "<option>#{shark}</option>"}
output = options.join("\n")
print output

   
   
Output
<option>Hammerhead</option> <option>Great White</option> <option>Tiger</option> <option>Whale</option>

Instead of converting an array to a string, you might want to get a total of its contents or perform some other kind of transformation that results in a single value. That’s up next.

与其将数组转换为字符串,不如要获取其全部内容或执行某种其他转换以产生单个值的转换。 接下来。

将数组简化为单个值 (Reducing Arrays to a Single Value)

When you’re working with a set of data, you may find that you need to rull the data up into a single value, such as a sum. One way you might do this is by using a variable and the each method:

当使用一组数据时,您可能会发现需要将数据汇总为单个值,例如总和。 一种可能的方法是使用变量和each方法:

result = 0
[1, 2, 3].each {|num| result += num}
print result

   
   
Output
6

You can use the reduce method to do this instead. The reduce method iterates over an array and keeps a running total by executing a binary operation for each element.

您可以使用reduce方法来代替。 reduce方法通过对每个元素执行二进制操作来遍历数组并保持运行总计。

The reduce method accepts an initial value for the result, as well as a block with two local values: a reference to the result and a reference to the current element. Inside of the block, you specify the logic to compute the end result.

reduce方法接受结果的初始值,以及具有两个局部值的块:对结果的引用和对当前元素的引用。 在块内部,指定逻辑以计算最终结果。

Since we want to sum up the array, we’ll initialize the result to 0 and then add the current value to the result in the block:

因为我们要对数组求和,所以我们将结果初始化为0 ,然后将当前值添加到块中的结果中:

output = [1,2,3].reduce(0) {|result, current| result += current }
print output

   
   
Output
6

If you plan to initialize the result to 0, you can omit the argument and just pass the block. This will automatically set the result to the first value in the array:

如果计划将结果初始化为0 ,则可以忽略参数,而只需传递该块。 这将自动将结果设置为数组中的第一个值:

output = [1,2,3].reduce {|result, current| result += current }
print output

   
   
Output
6

The reduce method also you specify a binary method, or a method on one object that accepts another object as its argument, which it will execute for each entry in the array. reduce then uses the results to create a single value.

reduce方法还可以指定一个二进制方法 ,或在一个对象上接受另一个对象作为其参数的方法,它将对数组中的每个条目执行该方法。 reduce然后使用结果创建单个值。

When you write 2 + 2 in Ruby, you’re actually invoking the + method on the integer 2:

当您在Ruby中编写2 + 2时,实际上是在整数2上调用+方法:

2.+(2)   # 4

Ruby uses some syntactic sugar so you can express it as 2 + 2.

Ruby使用一些语法糖,因此您可以将其表示为2 + 2

The reduce method lets you specify a binary method by passing its name as a symbol. That means you can pass :+ to the reduce method to sum the array:

通过reduce方法,您可以通过将其名称作为符号传递来指定二进制方法。 这意味着您可以将:+传递给reduce方法对数组求和:

output = [1, 2, 3].reduce(:+)   
print output

   
   
Output
6

You can use reduce to do more than just add up lists of numbers though. You can use it to transform values. Remember that reduce reduces an array to a single value. But there’s no rule that says ther single value can’t be another array.

但是,您可以使用reduce来做更多的事情,而不仅仅是累加数字列表。 您可以使用它来转换值。 请记住, reduce将数组减少为单个值。 但是没有规则说单个值不能是另一个数组。

Let’s say we have a list of values that we need to convert to integers. but we only want the values that can be converted to integers.

假设我们有一个需要转换为整数的值列表。 但是我们只希望可以将其转换为整数的值。

We could use reject to throw out the non-numeric values, and then use map to convert the remaining values to integers. But we can do it all in one step with reduce. Here’s how.

我们可以使用reject丢弃非数字值,然后使用map将剩余的值转换为整数。 但是,使用reduce可以一步一步完成所有工作。 这是如何做。

Use an empty array as the initialization value. Then, in the block, convert the current value to an Integer with the Integer method. If the value can’t be converted to an Integer, Integer will raise an exception, which you can catch and assign nil to the value.

使用一个空数组作为初始化值。 然后,在该块中,使用Integer方法将当前值转换为Integer 。 如果该值不能被转换为整数, Integer将引发异常,可以捕获并分配nil的值。

Then take the value and put it in the array, but only if it’s not nil.

然后取值并将其放在数组中,但前提是它不是nil

Here’s what the code looks like. Try this out:

代码如下所示。 试试看:

convert_array_of_values.rb
convert_array_of_values.rb
values = ["1", "2", "a", "3"]
integers = values.reduce([]) do |array, current|
  val = Integer(current) rescue nil
  array.push(val) unless val.nil?
  array
end
print integers

   
   
Output
[1,2,3]

Whenever you have a list of elements that you need to convert to a single value, you might be able to solve it with reduce.

只要有需要转换为单个值的元素列表,便可以使用reduce来解决。

结论 (Conclusion)

In this tutorial, you used several methods to work with arrays. You grabbed individual elements, retrieved values by searching through the array, sorted elements, and you transformed the data, creating new arrays, strings, and totals. You can apply these concepts to solve many common programming problems with Ruby.

在本教程中,您使用了几种方法来处理数组。 您可以抓取单个元素,通过搜索数组,排序元素来检索值,然后转换数据,创建新的数组,字符串和总计。 您可以应用这些概念来解决Ruby的许多常见编程问题。

Be sure to look at these related tutorials to continue exploring how to work with data in Ruby:

请务必查看这些相关教程,以继续探索如何在Ruby中处理数据:

翻译自: https://www.digitalocean.com/community/tutorials/how-to-use-array-methods-in-ruby

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值