How to get the first key and value pair from a hash table in Ruby

You can just do

key, value = hash.first

or if you prefer:

key = hash.keys[0]
value = hash.values[0]

Then maybe:

new_hash = {key => value}

There is a shorter answer that does not require you to use extra variables:

h = { "a" => 100, "b" => 200 , "c" => 300, "d" => 400, "e" => 500}
Hash[*h.first] #=> {"a" => 100}

Or if you want to retrieve a key/value at a any single position

Hash[*h.to_a.at(1)] #=> {"b" => 200}

Or retrieve a key/values from a range of positions:

 Hash[h.to_a[1,3]] #=> {"b"=>200, "c"=>300, "d"=>400}

Tags:

Ruby

Hash