File tree Expand file tree Collapse file tree 2 files changed +48
-1
lines changed Expand file tree Collapse file tree 2 files changed +48
-1
lines changed Original file line number Diff line number Diff line change @@ -101,7 +101,8 @@ def skip(count)
101
101
# given predicate (a function which performs a test on the value and
102
102
# should return a boolean).
103
103
#
104
- # If the stream is empty, the returned value is true.
104
+ # If the stream is empty, the returned value is true and the predicate
105
+ # is not called at all.
105
106
#
106
107
# This is a terminal operation.
107
108
# +test+:: A function which should perform some boolean test on the
@@ -113,6 +114,24 @@ def all_match(&test)
113
114
true
114
115
end
115
116
117
+ # Returns true if any of the elements of the Stream are matching
118
+ # the given predicate (a function which performs a test on the value and
119
+ # should return a boolean). Iteration will stop at the first match.
120
+ #
121
+ # If the stream is empty, the returned value is false and the predicate
122
+ # is not called at all.
123
+ #
124
+ # This is a terminal operation.
125
+ #
126
+ # +test+:: A function which should perform some boolean test on the
127
+ # given value.
128
+ def any_match ( &test )
129
+ @array . each do |val |
130
+ return true if test . call ( val )
131
+ end
132
+ false
133
+ end
134
+
116
135
# Collect the stream's data into an array and return it.
117
136
# This is a terminal operation.
118
137
def collect
Original file line number Diff line number Diff line change @@ -258,5 +258,33 @@ def test_not_all_elements_match
258
258
'Expected false because not all elements are a match!'
259
259
)
260
260
end
261
+
262
+ # FromArray.any_match returns true if one element matches.
263
+ def test_any_element_matches
264
+ stream = FromArray . new ( [ 2 , 4 , 6 , 8 ] )
265
+ assert (
266
+ stream . any_match { |val | val == 4 } ,
267
+ 'Stream contains element 4, it should match!'
268
+ )
269
+ end
270
+
271
+ # FromArray.any_match returns true if all elements match.
272
+ def test_any_match_all
273
+ stream = FromArray . new ( [ 2 , 4 , 6 , 8 ] )
274
+ assert (
275
+ stream . any_match { |val | val %2 == 0 } ,
276
+ 'All elements are even, it should match!'
277
+ )
278
+ end
279
+
280
+ # FromArray.any_match returns false and the predicate is never called,
281
+ # because the stream is empty.
282
+ def test_any_match_empty
283
+ stream = FromArray . new ( [ ] )
284
+ assert (
285
+ !stream . any_match { raise ScriptError , 'Should not be called' } ,
286
+ 'Stream is empty, any_match should be false!'
287
+ )
288
+ end
261
289
end
262
290
end
You can’t perform that action at this time.
0 commit comments