Let's take this example:
d = {"a" => 1, "b" => 2, "c" => 3, "d" => 4}
Since hashes are now ordered, I might want to get data from a
to b
or from c
to d
. The problem is that I can't do d[0..1]
or d[2..3]
.
I could however do:
irb > d.to_a[0..1]
=> [["a", 1], ["b", 2]]
... but this feels messy and I don't want to cast my hash for an operation like this.
Is there a cleaner solution to handle this?
# Holy Grail
irb > d[0..1]
=> {"a" => 1, "b" => 2}
I can see how to program myself such a method, but there might be something native already done that I could use...?
Well you could do :
> a = {"a" => 1, "b" => 2, "c" => 3, "d" => 4}
> a.slice(*a.keys[0..1])
=> {"a" => 1, "b" => 1}
At least the hash is not cast, but it's still not very elegant in my opinion.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With