Skip to content

Instantly share code, notes, and snippets.

@edvardm
Created October 27, 2011 05:56
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save edvardm/1318874 to your computer and use it in GitHub Desktop.
Save edvardm/1318874 to your computer and use it in GitHub Desktop.
Small convenience method to build stuff on the fly
module Enumerable
# like inject, but returns accumulator instead. Instead of writing
# [1, 2].inject({}) {|h, i| h[i] = 2*i; h }
# just say
# [1, 2].infuse({}) {|h, i| h[i] = 2*i } # -> {1 => 2, 2 => 4}
def infuse(init, &block)
inject(init) { |t, i| block.call(t, i); t }
end
end
describe "EnumExtensions" do
describe Array do
it "should work with empty Array" do
[].infuse({}) { |a, i| a[i] = 1 }.should be_empty
end
it "should work with array containing elements" do
[1, 2].infuse({}) { |a, i| a[i] = 2*i }.should == {1 => 2, 2 => 4}
end
it "should infuse a hash" do
[1, 2].infuse_hash { |a, i| a[i] = 2*i }.should == {1 => 2, 2 => 4}
end
end
describe Hash do
it "should work with empty Hash" do
{}.infuse([]) { |a, (k, v)| a << 1 }.should be_empty
end
it "should work with hash containing elements" do
{:foo => 1, :bar => 2}.infuse([]) do |a, (k, v)|
a << [k, v]
end.should == [[:foo, 1], [:bar, 2]]
end
it "should infuse a hash" do
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment