Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get only a subset of an ordered hash in Ruby 1.9?

Tags:

ruby

hash

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...?

like image 839
marcgg Avatar asked Oct 06 '11 15:10

marcgg


1 Answers

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.

like image 171
DuoSRX Avatar answered Oct 05 '22 07:10

DuoSRX