Created
June 16, 2011 03:37
-
-
Save igrep/1028628 to your computer and use it in GitHub Desktop.
(UNNAMED) generator expression like Python in Ruby
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env ruby | |
# -*- coding: utf-8 -*- | |
$VERBOSE = true | |
=begin | |
Maybe usable as generator expression in Python | |
requires ruby1.9 or facets ( >= 2.9.1 ) | |
=end | |
if RUBY_VERSION < '1.9' | |
require 'rubygems' | |
require 'facets/enumerator' | |
end | |
module Enumerable | |
def _unnamed_enum_compact_map &blk | |
Enumerator.new{|y| | |
self.each{|e| | |
res = blk.call e | |
y.yield res unless res.nil? | |
} | |
} | |
end | |
end | |
if __FILE__ == $PROGRAM_NAME | |
#mapper #predicate | |
enum = (1..100)._unnamed_enum_compact_map{|x| x**2 if x.odd? } | |
p enum.next #=> 1 | |
p enum.next #=> 9 | |
p enum.take( 5 ) #=> [1, 9, 25, 49, 81] | |
#case maybe that doesn't work as you expect. | |
#if an item is mapped into nil by the mapper, | |
#it's omitted even the predicate returns true. | |
enum = %w/ruby perl python php javascript/._unnamed_enum_compact_map{|s| | |
#mapper #predicate | |
s =~ /p/ if s.length > 3 | |
} | |
p enum.next #=> 0 ( *p*erl: not nil, the value of '"ruby" =~ /p/' ) | |
p enum.next #=> 0 ( *p*yhon ) | |
#'php' was omitted because '"php".length > 3' is false | |
p enum.next #=> 8 ( javascri*p*t ) | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment