@@ -612,8 +612,8 @@ class Hash(K, V)
612
612
# Returns the first key if it exists, or returns `nil`.
613
613
#
614
614
# ```
615
- # hash = {"foo " => "bar "}
616
- # hash.first_key? # => "foo "
615
+ # hash = {"foo1 " => "bar1", "foz2" => "baz2 "}
616
+ # hash.first_key? # => "foo1 "
617
617
# hash.clear
618
618
# hash.first_key? # => nil
619
619
# ```
@@ -626,11 +626,52 @@ class Hash(K, V)
626
626
@first .not_nil!.value
627
627
end
628
628
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
+ # ```
630
637
def first_value ?
631
638
@first .try & .value
632
639
end
633
640
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
+
634
675
# Deletes and returns the first key-value pair in the hash,
635
676
# or raises `IndexError` if the hash is empty.
636
677
#
0 commit comments