diff --git a/spec/std/hash_spec.cr b/spec/std/hash_spec.cr index f610e5a03ccf..c07d015eb898 100644 --- a/spec/std/hash_spec.cr +++ b/spec/std/hash_spec.cr @@ -482,6 +482,16 @@ describe "Hash" do h.first_value.should eq(2) end + it "gets last key" do + h = {1 => 2, 3 => 4} + h.last_key.should eq(3) + end + + it "gets last value" do + h = {1 => 2, 3 => 4} + h.last_value.should eq(4) + end + it "shifts" do h = {1 => 2, 3 => 4} h.shift.should eq({1, 2}) diff --git a/src/hash.cr b/src/hash.cr index f7c1493341da..04b12ecfeff8 100644 --- a/src/hash.cr +++ b/src/hash.cr @@ -612,8 +612,8 @@ class Hash(K, V) # Returns the first key if it exists, or returns `nil`. # # ``` - # hash = {"foo" => "bar"} - # hash.first_key? # => "foo" + # hash = {"foo1" => "bar1", "foz2" => "baz2"} + # hash.first_key? # => "foo1" # hash.clear # hash.first_key? # => nil # ``` @@ -626,11 +626,53 @@ class Hash(K, V) @first.not_nil!.value end - # Similar to `#first_key?`, but returns its value. + # Returns the last value if it exists, or returns `nil`. + # + # ``` + # hash = {"foo1" => "bar1", "foz2" => "baz2"} + # hash.first_value? # => "bar1" + # hash.clear + # hash.first_value? # => nil + # ``` def first_value? @first.try &.value end + # Returns the last key in the hash. + def last_key + @last.not_nil!.key + end + + # Returns the last key if it exists, or returns `nil`. + # + # ``` + # hash = {"foo1" => "bar1", "foz2" => "baz2"} + # hash.last_key? # => "foz2" + # hash.clear + # hash.last_key? # => nil + # ``` + def last_key? + @last.try &.key + end + + # Returns the last value in the hash. + def last_value + @last.not_nil!.value + end + + # Returns the last value if it exists, or returns `nil`. + # + # ``` + # hash = {"foo1" => "bar1", "foz2" => "baz2"} + # hash.last_value? # => "baz2" + # hash.clear + # hash.last_value? # => nil + # ``` + def last_value? + @last.try &.value + end + + # Deletes and returns the first key-value pair in the hash, # or raises `IndexError` if the hash is empty. #