# Ruby Enumerator的各种迭代

## Enumerator迭代

Mix-in Enumerator获得的迭代方法

### each_cons()

each_cons(n) { ... } → nil
each_cons(n) → an_enumerator

(1..10).each_cons(3) { |a| p a }
## 输出：
=begin
[1, 2, 3]
[2, 3, 4]
[3, 4, 5]
[4, 5, 6]
[5, 6, 7]
[6, 7, 8]
[7, 8, 9]
[8, 9, 10]
=end

### each_slice()

each_slice(n) { ... } → nil
each_slice(n) → an_enumerator

(1..10).each_slice(3) { |a| p a }
## 输出：
=begin
[1, 2, 3]
[4, 5, 6]
[7, 8, 9]
[10]
=end

### each_with_index()

each_with_index { |obj, i| block } → enum
each_with_index → an_enumerator

hash = Hash.new
%w(cat dog wombat).each_with_index { |item, index|
hash[item] = index
}
hash   # {"cat"=>0, "dog"=>1, "wombat"=>2}

### with_index()

e.with_index(offset = 0) {|(*args), idx| ... }
e.with_index(offset = 0)

a = %w(a b c d e)

a.each.with_index do |x,idx|
p "index: #{idx}, value: #{x}"
end
## 输出：
=begin
"index: 0, value: a"
"index: 1, value: b"
"index: 2, value: c"
"index: 3, value: d"
"index: 4, value: e"
=end

a.each.with_index(2) do |x,idx|
p "index: #{idx}, value: #{x}"
end
## 输出：
=begin
"index: 2, value: a"
"index: 3, value: b"
"index: 4, value: c"
"index: 5, value: d"
"index: 6, value: e"
=end

### each_with_object()

each_with_object(obj) { |(*args), memo_obj| ... } → obj
each_with_object(obj) → an_enumerator

evens = (1..10).each_with_object([]) { |i, a| a << i*2 }
#=> [2, 4, 6, 8, 10, 12, 14, 16, 18, 20]

a = ("a".."c").each_with_object("x") {|i,str| str += i}
b = ("a".."c").each_with_object("x") {|i,str| str << i}
p a      # "x"
p b      # "xabc"

str << i的方式是直接在原字符串上追加字母的，str所引用的对象一直都未改变，最后返回的原始对象也是更改后的。

a = (1..10).each_with_object(0) {|i, sum| sum += i}
p a   # 0

a = (1..10).inject(:+)
p a  # 55

a = (1..10).inject {|sum, x| sum + x}
p a  # 55

### each_entry()

class Foo
include Enumerable
def each
yield 1
yield 1, 2
yield
end
end
Foo.new.each_entry{ |o| p o }

## 输出：
=begin
1
[1, 2]
nil
=end
posted @ 2019-04-15 11:31 骏马金龙 阅读(...) 评论(...) 编辑 收藏