Skip to content

Commit 3138b52

Browse files
j8rRX14
authored andcommittedApr 7, 2018
Add Hash#last_key and Hash#last_value (#5760)
1 parent 7d64756 commit 3138b52

File tree

2 files changed

+54
-3
lines changed

2 files changed

+54
-3
lines changed
 

Diff for: ‎spec/std/hash_spec.cr

+10
Original file line numberDiff line numberDiff line change
@@ -482,6 +482,16 @@ describe "Hash" do
482482
h.first_value.should eq(2)
483483
end
484484

485+
it "gets last key" do
486+
h = {1 => 2, 3 => 4}
487+
h.last_key.should eq(3)
488+
end
489+
490+
it "gets last value" do
491+
h = {1 => 2, 3 => 4}
492+
h.last_value.should eq(4)
493+
end
494+
485495
it "shifts" do
486496
h = {1 => 2, 3 => 4}
487497
h.shift.should eq({1, 2})

Diff for: ‎src/hash.cr

+44-3
Original file line numberDiff line numberDiff line change
@@ -612,8 +612,8 @@ class Hash(K, V)
612612
# Returns the first key if it exists, or returns `nil`.
613613
#
614614
# ```
615-
# hash = {"foo" => "bar"}
616-
# hash.first_key? # => "foo"
615+
# hash = {"foo1" => "bar1", "foz2" => "baz2"}
616+
# hash.first_key? # => "foo1"
617617
# hash.clear
618618
# hash.first_key? # => nil
619619
# ```
@@ -626,11 +626,52 @@ class Hash(K, V)
626626
@first.not_nil!.value
627627
end
628628

629-
# Similar to `#first_key?`, but returns its value.
629+
# Returns the first value if it exists, or returns `nil`.
630+
#
631+
# ```
632+
# hash = {"foo1" => "bar1", "foz2" => "baz2"}
633+
# hash.first_value? # => "bar1"
634+
# hash.clear
635+
# hash.first_value? # => nil
636+
# ```
630637
def first_value?
631638
@first.try &.value
632639
end
633640

641+
# Returns the last key in the hash.
642+
def last_key
643+
@last.not_nil!.key
644+
end
645+
646+
# Returns the last key if it exists, or returns `nil`.
647+
#
648+
# ```
649+
# hash = {"foo1" => "bar1", "foz2" => "baz2"}
650+
# hash.last_key? # => "foz2"
651+
# hash.clear
652+
# hash.last_key? # => nil
653+
# ```
654+
def last_key?
655+
@last.try &.key
656+
end
657+
658+
# Returns the last value in the hash.
659+
def last_value
660+
@last.not_nil!.value
661+
end
662+
663+
# Returns the last value if it exists, or returns `nil`.
664+
#
665+
# ```
666+
# hash = {"foo1" => "bar1", "foz2" => "baz2"}
667+
# hash.last_value? # => "baz2"
668+
# hash.clear
669+
# hash.last_value? # => nil
670+
# ```
671+
def last_value?
672+
@last.try &.value
673+
end
674+
634675
# Deletes and returns the first key-value pair in the hash,
635676
# or raises `IndexError` if the hash is empty.
636677
#

0 commit comments

Comments
 (0)
Please sign in to comment.