Ruby:在每个映射,注入,each_with_index和each_with_object之间进行选择 [英] Ruby : Choosing between each, map, inject, each_with_index and each_with_object
问题描述
当我多年前开始编写Ruby时,花了一段时间才了解 each and 地图。只有当我发现所有其他 Enumerable 和 Array 方法。
在官方文档和许多的帮助下 StackOverflow 下面是我花更长的时间理解的: 我希望这个问题不是重复的:我对为什么?更感兴趣。比什么?或How?,我认为它可以帮助Ruby新手。 更多 tl; dr 如何在每个map,inject,each_with_index和each_with_object之间进行选择? 当您需要generic时,使用 使用 使用 使用 When I started writing Ruby many years ago, it took me a while to understand the difference between each and map. It only got worse when I discovered all the other Enumerable and Array methods. With the help of the official documentation and many StackOverflow questions, I slowly began to understand what those methods did. Here is what took me even longer to understand though : I hope this question isn't a duplicate : I'm more interested in the "Why?" than the "What?" or "How?", and I think it could help Ruby newcomers. A more tl;dr answer: How to choose between each, map, inject, each_with_index and each_with_object?
Use Use Use Use Uses for 这篇关于Ruby:在每个映射,注入,each_with_index和each_with_object之间进行选择的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
$ b
blockquote>
#each
迭代并且不关心结果。例如 - 你有数字,你想打印每个数字的绝对值:
numbers.each {| number | puts number.abs}
#map
当你想要一个新的列表,其中每个元素通过变换原始元素以某种方式形成。例子 - 你有数字,你想得到他们的正方形:
numbers.map {| number |数字** 2}
#inject
当你想以某种方式将整个列表减少到一个单一的值。例子 - 你有数字,你想得到它们的总和:
numbers.inject(&:+)
#each_with_index
code> #each ,除了您还希望每个元素都有索引:
数字.each_with_index {|数字,索引| #编号#位于#{index}位置}
#each_with_object
更受限制。最常见的情况是,如果你需要类似于 #inject
的东西,但想要一个新的集合(而不是奇异值),这不是原始的直接映射。示例 - 数字直方图(频率):
numbers.each_with_object({}){|数字,直方图|直方图[编号] =直方图[编号] .to_i.next}
#each
when you want "generic" iteration and don't care about the result. Example - you have numbers, you want to print the absolute value of each individual number:numbers.each { |number| puts number.abs }
#map
when you want a new list, where each element is somehow formed by transforming the original elements. Example - you have numbers, you want to get their squares:numbers.map { |number| number ** 2 }
#inject
when you want to somehow reduce the entire list to one single value. Example - you have numbers, you want to get their sum:numbers.inject(&:+)
#each_with_index
in the same situation as #each
, except you also want the index with each element:numbers.each_with_index { |number, index| puts "Number #{number} is on #{index} position" }
#each_with_object
are more limited. The most common case is if you need something similar to #inject
, but want a new collection (as opposed to singular value), which is not a direct mapping of the original. Example - number histogram (frequencies):numbers.each_with_object({}) { |number, histogram| histogram[number] = histogram[number].to_i.next }