views:

214

answers:

1

Python's itertools module provides a lots of goodies with respect to processing an iterable/iterator by use of generators. For example,

permutations(range(3)) --> 012 021 102 120 201 210

combinations('ABCD', 2) --> AB AC AD BC BD CD

[list(g) for k, g in groupby('AAAABBBCCD')] --> AAAA BBB CC D

What are the equivalent in Ruby?

By equivalent, I mean fast and memory efficient (Python's itertools module is written in C).

+10  A: 

Array#permutation, Array#combination and Enumerable#group_by are defined in ruby since 1.8.7. If you're using 1.8.6 you can get equivalent methods from facets or active_support or backports.

Example Usage:

[0,1,2].permutation.to_a
#=> [[0, 1, 2], [0, 2, 1], [1, 0, 2], [1, 2, 0], [2, 0, 1], [2, 1, 0]]

[0,1,2,3].combination(2).to_a
#=> [[0, 1], [0, 2], [0, 3], [1, 2], [1, 3], [2, 3]]

[0,0,0,1,1,2].group_by {|x| x}.map {|k,v| v}
#=> [[0, 0, 0], [1, 1], [2]]

[0,1,2,3].group_by {|x| x%2}
#=> {0=>[0, 2], 1=>[1, 3]}
sepp2k