Alex Rivera | Logout

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

Asked 2011-10-06T15:06:02.440
12

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

Edit
Report

1 Answer

2

Probably there's a better way to do it but this is an idea:

class Hash
    def slice_by_index(a, b = nil)  
        k = if a.is_a?(Range)
            keys[a]
        elsif b.nil?
            [keys[a]]
        else
            keys[a,b]
        end
        k.inject({}){|h, k| h[k] = self[k] ; h }
    end
end

h = {"a" => 1, "b" => 2, "c" => 3, "d" => 4}
p h.slice_by_index(1..3) #range
p h.slice_by_index(2) #single element
p h.slice_by_index(0,3) #start, lenght
answered 2011-10-06T18:23:40.523

Your Answer