array_enumerator 0.0.2 → 0.0.3

Sign up to get free protection for your applications and to get access to all the features.
data/VERSION CHANGED
@@ -1 +1 @@
1
- 0.0.2
1
+ 0.0.3
@@ -5,7 +5,7 @@
5
5
 
6
6
  Gem::Specification.new do |s|
7
7
  s.name = %q{array_enumerator}
8
- s.version = "0.0.2"
8
+ s.version = "0.0.3"
9
9
 
10
10
  s.required_rubygems_version = Gem::Requirement.new(">= 0") if s.respond_to? :required_rubygems_version=
11
11
  s.authors = ["Kasper Johansen"]
@@ -47,6 +47,49 @@ class Array_enumerator
47
47
  end
48
48
  end
49
49
 
50
+ #This method should only be used with 'each_index'.
51
+ def [](key)
52
+ if @each_index and @each_index.key?(key)
53
+ ret = @each_index[key]
54
+ @each_index.delete(key)
55
+ return ret
56
+ end
57
+
58
+ raise "This only works when also using 'each_index'. Invalid key: '#{key}'."
59
+ end
60
+
61
+ #Yields each count-key and caches element for returning it by using the []-method.
62
+ def each_index(&block)
63
+ enum = Enumerator.new do |yielder|
64
+ begin
65
+ @each_index = {}
66
+
67
+ count = 0
68
+ self.each do |ele|
69
+ #Remove previous element to not take up memory.
70
+ count_before = count - 1
71
+ @each_index.delete(count_before) if @each_index.key?(count_before)
72
+
73
+ #Add current element to cache.
74
+ @each_index[count] = ele
75
+ yield(count)
76
+
77
+ #Increase count for next run.
78
+ count += 1
79
+ end
80
+ ensure
81
+ @each_index = nil
82
+ end
83
+ end
84
+
85
+ if block
86
+ enum.each(&block)
87
+ return nil
88
+ else
89
+ return enum
90
+ end
91
+ end
92
+
50
93
  #Returns a enumerator that can yield the all the lements (both cached and future un-cached ones).
51
94
  def to_enum
52
95
  check_corrupted
@@ -128,4 +128,17 @@ describe "ArrayEnumerator" do
128
128
  end
129
129
  end
130
130
  end
131
+
132
+ it "each_index" do
133
+ arr = %w[a b c d e f g]
134
+ ae = Array_enumerator.new(arr.to_enum)
135
+
136
+ expect = 0
137
+ ae.each_index do |num|
138
+ raise "Expected #{expect} but got: #{num}" if num != expect
139
+ ele = ae[num]
140
+ raise "Expected #{arr[num]} but got: #{ele}" if ele != arr[num]
141
+ expect += 1
142
+ end
143
+ end
131
144
  end
metadata CHANGED
@@ -2,7 +2,7 @@
2
2
  name: array_enumerator
3
3
  version: !ruby/object:Gem::Version
4
4
  prerelease:
5
- version: 0.0.2
5
+ version: 0.0.3
6
6
  platform: ruby
7
7
  authors:
8
8
  - Kasper Johansen
@@ -104,7 +104,7 @@ required_ruby_version: !ruby/object:Gem::Requirement
104
104
  requirements:
105
105
  - - ">="
106
106
  - !ruby/object:Gem::Version
107
- hash: 813322090081366183
107
+ hash: -947760670988037179
108
108
  segments:
109
109
  - 0
110
110
  version: "0"