Hash#first for ruby 1.8.6

Just got some failing specs from our 1.8.6 test runner, when using OrderedHash#first, so we fix that…

# add {}.first if its not there (1.8.6)
unless {}.respond_to?(:first)
  class Hash
    def first
      return if keys.empty?
      [keys.first, self[keys.first]]
    end
  end
end
Advertisements

2 thoughts on “Hash#first for ruby 1.8.6

  1. I ran into the same issue a while ago. Actually the method is missing on the Enumerable module and not only the Hash class, but it is still quite easy to implement a fully compliant back port. It also supports the optional length argument to fetch more the one element.

    The code was inspired by JRuby’s implementation, but I cannot find the relevant lines any more. They might be gone.

    I think Rubinius’ implementation is even more straight forward. It relies on take, which is also not part of 1.8.6, but can be easily added as well.

    http://github.com/evanphx/rubinius/blob/master/kernel/common/enumerable.rb

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s