Given a hash of arbitrary length, how do i return only a number of key value pairs (as a new hash) up to a certain point given as an integer?
For example:
hash = {a: 6, b: 2, c: 1, d: 5, e: 3, f: 4}
desiredlength = 3
desiredoutput = hash = {a: 6, b: 2, c: 1}
(In my example I deliberately gave the hash values as random numbers, since I'd like a method that does not rely on the content of the values like .sort, just the order in which they appear in the hash)
This seems like it should be simple but I haven't found a good method yet.
I did come up with this method:
Hash[hash.to_a[0, desiredlength]]
This takes the original hash, turns it into an array, and converts the range of 0 to desiredlength back into a hash
... but it feels super clunky and rubocop doesn't like it
CodePudding user response:
As with many things in ruby, There's More Than One Way To Do It.
Here's one:
hash = {a: 6, b: 2, c: 1, d: 5, e: 3, f: 4}
hash.first(3).to_h
#=> {:a=>6, :b=>2, :c=>1}
# Or, similarly:
Hash[hash.first(3)]
See: Enumberable#first
.
CodePudding user response:
hash = {a: 6, b: 2, c: 1, d: 5, e: 3, f: 4}
desiredlength = 3
hash.select { (desiredlength -= 1) >= 0 }
#=> {a: 6, b: 2, c: 1 }
See Hash#select.
Another way:
hash.slice(*hash.keys.first(desiredlength))
#=> {a: 6, b: 2, c: 1 }
See Hash#slice.