在 Enumerable#collect 中跳过迭代 [英] Skip over iteration in Enumerable#collect

查看:39
本文介绍了在 Enumerable#collect 中跳过迭代的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

(1..4).collect do |x|
  next if x == 3
  x + 1
end # => [2, 3, nil, 5]
    # desired => [2, 3, 5]

如果满足 next 的条件,collectnil 放入数组中,而我想要做的是放入 <如果满足条件,则返回数组中的 em>no 元素.这是否可能不调用 delete_if { |x|x == nil } 在返回的数组上?

If the condition for next is met, collect puts nil in the array, whereas what I'm trying to do is put no element in the returned array if the condition is met. Is this possible without calling delete_if { |x| x == nil } on the returned array?

(使用 Ruby 1.8.7;我的代码摘录是高度抽象的)

(Using Ruby 1.8.7; my code excerpt is heavily abstracted)

推荐答案

有方法 Enumerable#reject 仅用于此目的:

There is method Enumerable#reject which serves just the purpose:

(1..4).reject{|x| x == 3}.collect{|x| x + 1}

直接使用一种方法的输出作为另一种方法的输入的做法称为方法链,在 Ruby 中非常普遍.

The practice of directly using an output of one method as an input of another is called method chaining and is very common in Ruby.

顺便说一句,map(或collect)用于将输入可枚举直接映射到输出.如果您需要输出不同数量的元素,很可能您需要另一种 Enumerable 方法.

BTW, map (or collect) is used for direct mapping of input enumerable to the output one. If you need to output different number of elements, chances are that you need another method of Enumerable.

如果您对某些元素迭代两次这一事实感到困扰,您可以使用基于 inject(或其类似方法 each_with_object):

If you are bothered by the fact that some of the elements are iterated twice, you can use less elegant solution based on inject (or its similar method named each_with_object):

(1..4).each_with_object([]){|x,a| a << x + 1 unless x == 3}

这篇关于在 Enumerable#collect 中跳过迭代的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆