summaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
authorMatt Robinson <matt@puppetlabs.com>2011-04-08 12:06:17 -0700
committerMatt Robinson <matt@puppetlabs.com>2011-04-08 12:06:17 -0700
commit08a53bd452ca095df0d44a8d6b41e7088f6c449e (patch)
tree5869f3237987b5d924a0517bd4bc2e6835e00b1d
parente0a2e9180c20b664900586d7dedacd4172c24f6a (diff)
parent3094d423c498640f01d267ca7589533f862e9ac4 (diff)
downloadpuppet-08a53bd452ca095df0d44a8d6b41e7088f6c449e.tar.gz
puppet-08a53bd452ca095df0d44a8d6b41e7088f6c449e.tar.xz
puppet-08a53bd452ca095df0d44a8d6b41e7088f6c449e.zip
Merge branch 'ticket/next/maint-backport_array_combination' into next
* ticket/next/maint-backport_array_combination: maint: Add Array combinations method
-rw-r--r--lib/puppet/util/monkey_patches.rb14
-rw-r--r--spec/unit/util/monkey_patches_spec.rb23
2 files changed, 37 insertions, 0 deletions
diff --git a/lib/puppet/util/monkey_patches.rb b/lib/puppet/util/monkey_patches.rb
index a93c66b07..10a268409 100644
--- a/lib/puppet/util/monkey_patches.rb
+++ b/lib/puppet/util/monkey_patches.rb
@@ -90,3 +90,17 @@ if RUBY_VERSION == '1.8.1' || RUBY_VERSION == '1.8.2'
r
}
end
+
+class Array
+ # Ruby < 1.8.7 doesn't have this method but we use it in tests
+ def combination(num)
+ return [] if num < 0 || num > size
+ return [[]] if num == 0
+ return map{|e| [e] } if num == 1
+ tmp = self.dup
+ self[0, size - (num - 1)].inject([]) do |ret, e|
+ tmp.shift
+ ret += tmp.combination(num - 1).map{|a| a.unshift(e) }
+ end
+ end unless method_defined? :combination
+end
diff --git a/spec/unit/util/monkey_patches_spec.rb b/spec/unit/util/monkey_patches_spec.rb
index 8bfcd900e..fb2103ea9 100644
--- a/spec/unit/util/monkey_patches_spec.rb
+++ b/spec/unit/util/monkey_patches_spec.rb
@@ -31,3 +31,26 @@ describe "yaml deserialization" do
obj.foo.should == 100
end
end
+
+# In Ruby > 1.8.7 this is a builtin, otherwise we monkey patch the method in
+describe "Array#combination" do
+ it "should fail if wrong number of arguments given" do
+ lambda { [1,2,3].combination() }.should raise_error(ArgumentError, /wrong number/)
+ lambda { [1,2,3].combination(1,2) }.should raise_error(ArgumentError, /wrong number/)
+ end
+
+ it "should return an empty array if combo size than array size or negative" do
+ [1,2,3].combination(4).to_a.should == []
+ [1,2,3].combination(-1).to_a.should == []
+ end
+
+ it "should return an empty array with an empty array if combo size == 0" do
+ [1,2,3].combination(0).to_a.should == [[]]
+ end
+
+ it "should all provide all combinations of size passed in" do
+ [1,2,3,4].combination(1).to_a.should == [[1], [2], [3], [4]]
+ [1,2,3,4].combination(2).to_a.should == [[1, 2], [1, 3], [1, 4], [2, 3], [2, 4], [3, 4]]
+ [1,2,3,4].combination(3).to_a.should == [[1, 2, 3], [1, 2, 4], [1, 3, 4], [2, 3, 4]]
+ end
+end