ruby 是否支持可枚举的 map_cons 方法或其等效方法?
Does ruby support an enumerable map_cons method or its equivalent?
Ruby 有一个方便的枚举函数 each_cons
。其中 "Iterates the given block for each array of consecutive elements." 这真是太好了。除了这绝对是一个 each
方法,它 return 在完成时为零,而不是像 map
那样循环的值数组。
但是,如果我遇到需要迭代可枚举类型的情况,获取一个元素及其缺点,然后对它们执行一些操作,然后 return 将它们返回到数组中,我该怎么办?通常,我会使用 map 来处理这种行为。但是 map_cons
不存在。
一个例子:
给定一个整数列表,我需要查看哪些整数重复,return 只包含这些整数的列表
[1, 1, 4, 5, 6, 2, 2] ## I need some function that will get me [1, 2]
我可以说:
[1, 1, 4, 5, 6, 2, 2].each_cons(2) {|e| e[0] if e[0] == e[1]}
但是,由于它 each
遍历数组,它将成功完成并在最后 return nil
。我需要它表现得像 map
而不是 each
。
ruby 支持这种行为吗?我完全是从错误的方向来的吗?
只需添加 map
?
[1, 1, 4, 5, 6, 2, 2].each_cons(2).map { |e| e[0] if e[0] == e[1] }
=> [1, nil, nil, nil, nil, 2]
each_cons 的文档以这个无辜的短语结尾:"If no block is given, returns an enumerator." Enumerable 的大多数方法都是这样做的。您可以使用枚举器做什么? Nothing truly impressive。但是 Enumerators 包括 Enumerable,它确实提供了大量强大的方法,map
就是其中之一。因此,正如 Stefan Pochmann 所做的那样:
[1, 1, 4, 5, 6, 2, 2].each_cons(2).map { |e| e[0] if e[0] == e[1] }
each_cons
调用时没有块,因此它 returns 是一个枚举器。 map
只是它的方法之一。
Ruby 有一个方便的枚举函数 each_cons
。其中 "Iterates the given block for each array of consecutive elements." 这真是太好了。除了这绝对是一个 each
方法,它 return 在完成时为零,而不是像 map
那样循环的值数组。
但是,如果我遇到需要迭代可枚举类型的情况,获取一个元素及其缺点,然后对它们执行一些操作,然后 return 将它们返回到数组中,我该怎么办?通常,我会使用 map 来处理这种行为。但是 map_cons
不存在。
一个例子:
给定一个整数列表,我需要查看哪些整数重复,return 只包含这些整数的列表
[1, 1, 4, 5, 6, 2, 2] ## I need some function that will get me [1, 2]
我可以说:
[1, 1, 4, 5, 6, 2, 2].each_cons(2) {|e| e[0] if e[0] == e[1]}
但是,由于它 each
遍历数组,它将成功完成并在最后 return nil
。我需要它表现得像 map
而不是 each
。
ruby 支持这种行为吗?我完全是从错误的方向来的吗?
只需添加 map
?
[1, 1, 4, 5, 6, 2, 2].each_cons(2).map { |e| e[0] if e[0] == e[1] }
=> [1, nil, nil, nil, nil, 2]
each_cons 的文档以这个无辜的短语结尾:"If no block is given, returns an enumerator." Enumerable 的大多数方法都是这样做的。您可以使用枚举器做什么? Nothing truly impressive。但是 Enumerators 包括 Enumerable,它确实提供了大量强大的方法,map
就是其中之一。因此,正如 Stefan Pochmann 所做的那样:
[1, 1, 4, 5, 6, 2, 2].each_cons(2).map { |e| e[0] if e[0] == e[1] }
each_cons
调用时没有块,因此它 returns 是一个枚举器。 map
只是它的方法之一。