EdvardM
10/27/2011 - 5:56 AM

Small convenience method to build stuff on the fly

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