Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP
Browse files

Merge pull request #7 from misfo/slice-and-except

Hash#slice and Hash#except
  • Loading branch information...
commit 8a3ea045b748ee0a411ba70be2cda6da07aa2ff5 2 parents 5edce74 + 3b4ff10
@harukizaemon harukizaemon authored
View
8 lib/hamster/hash.rb
@@ -127,6 +127,14 @@ def merge(other)
end
def_delegator :self, :merge, :+
+ def except(*keys)
+ keys.reduce(self) { |hash, key| hash.delete(key) }
+ end
+
+ def slice(*keys)
+ except(*self.keys - keys)
+ end
+
def keys
reduce(Hamster.set) { |keys, key, value| keys.add(key) }
end
View
31 spec/hamster/hash/except_spec.rb
@@ -0,0 +1,31 @@
+require 'spec_helper'
+
+require 'hamster/hash'
+
+describe Hamster::Hash do
+
+ describe "#except" do
+
+ before do
+ @hash = Hamster.hash("A" => "aye", "B" => "bee", "C" => "see", nil => "NIL")
+ end
+
+ describe "with only keys that the Hash has" do
+
+ it "returns a Hash without those values" do
+ @hash.except("B", nil).should == Hamster.hash("A" => "aye", "C" => "see")
+ end
+
+ end
+
+ describe "with keys that the Hash doesn't have" do
+
+ it "returns a Hash without the values that it had keys for" do
+ @hash.except("B", "A", 3).should == Hamster.hash("C" => "see", nil => "NIL")
+ end
+
+ end
+
+ end
+
+end
View
2  spec/hamster/hash/has_key_spec.rb
@@ -6,7 +6,7 @@
[:has_key?, :key?, :include?, :member?].each do |method|
- describe "#has_key?" do
+ describe "##{method}" do
before do
@hash = Hamster.hash("A" => "aye", "B" => "bee", "C" => "see", nil => "NIL", 2.0 => "two")
View
31 spec/hamster/hash/slice_spec.rb
@@ -0,0 +1,31 @@
+require 'spec_helper'
+
+require 'hamster/hash'
+
+describe Hamster::Hash do
+
+ describe "#slice" do
+
+ before do
+ @hash = Hamster.hash("A" => "aye", "B" => "bee", "C" => "see", nil => "NIL")
+ end
+
+ describe "with only keys that the Hash has" do
+
+ it "returns a Hash with only those values" do
+ @hash.slice("B", nil).should == Hamster.hash("B" => "bee", nil => "NIL")
+ end
+
+ end
+
+ describe "with keys that the Hash doesn't have" do
+
+ it "returns a Hash with only the values that have matching keys" do
+ @hash.slice("B", "A", 3).should == Hamster.hash("A" => "aye", "B" => "bee")
+ end
+
+ end
+
+ end
+
+end
Please sign in to comment.
Something went wrong with that request. Please try again.