Permalink
Browse files

Add Enumerable#grep: & Enumerable#grep:taking:

  • Loading branch information...
bakkdoor committed Jun 12, 2012
1 parent d9f276c commit 2d000e95adfe35ea6c9e841ec6697d7239e7dd96
Showing with 49 additions and 0 deletions.
  1. +33 −0 lib/enumerable.fy
  2. +16 −0 tests/enumerable.fy
View
@@ -744,5 +744,38 @@ class Fancy {
[take_while: predicate_block, drop_while: predicate_block]
}
+
+ def grep: pattern {
+ """
+ @pattern Pattern to be filtered by (via @Object#===@)
+ @return Elements in @self for which @pattern matches.
+
+ Example:
+ \"hello world\" grep: /[a-h]/ # => [\"h\", \"e\", \"d\"]
+ [\"hello\", \"world\", 1, 2, 3] grep: String # => [\"hello\", \"world\"]
+ """
+
+ select: |x| { pattern === x }
+ }
+
+ def grep: pattern taking: block {
+ """
+ @pattern Pattern to be filtered by (via @Object#===@)
+ @block @Block@ to be called with each element for which @pattern matches.
+ @return Return values of elements in @self called with @block for which @pattern matches.
+
+ Example:
+ \"hello world\" grep: /[a-h]/ taking: @{ upcase } # => [\"H\", \"E\", \"D\"]
+ [\"hello\", \"world\", 1, 2, 3] grep: String taking: 'upcase # => [\"HELLO\", \"WORLD\"]
+ """
+
+ result = []
+ each: |x| {
+ match x {
+ case pattern -> result << (block call: [x])
+ }
+ }
+ result
+ }
}
}
View
@@ -131,4 +131,20 @@ FancySpec describe: Fancy Enumerable with: {
(1,2,3) last: 3 . is: [1,2,3]
(1,2,3) last: 4 . is: [1,2,3]
}
+
+ it: "returns the elements for which a pattern matches" with: 'grep: when: {
+ "hello world" grep: /[a-h]/ . is: ["h", "e", "d"]
+ ["hello", "world", 1, 2, 3] grep: String . is: ["hello", "world"]
+ (1,2,3,4,5) grep: @{ < 2 } . is: [1] # blocks can be used as patterns, too :)
+ (1,2,3) grep: String . is: []
+ (1,2,3,4) grep: (2..3) . is: [2, 3]
+ }
+
+ it: "returns the values of calling a block for all elements for which a pattern matches" with: 'grep:taking: when: {
+ "hello world" grep: /[a-h]/ taking: 'upcase . is: ["H", "E", "D"]
+ ["hello", "world", 1, 2, 3] grep: String taking: 'upcase . is: ["HELLO", "WORLD"]
+ (1,2,3,4,5) grep: @{ < 2 } taking: 'doubled . is: [2]
+ (1,2,3) grep: String taking: 'to_s . is: []
+ (1,2,3,4) grep: (2..3) taking: 'to_s . is: ["2", "3"]
+ }
}

0 comments on commit 2d000e9

Please sign in to comment.