Hashes in 1.9 index

I

Iain Barnett

Since hashes in 1.9 retain their insert order, is there a built in way =
to get values by index as well as key?

For example:
h =3D { a: 17, b: 18, c: 19 }

puts h[1]
=3D> 19

Obviously that can't work, but there may be some other way I haven't =
found by looking through the docs? At the moment I'm using this:

class Hash
def by_index( n )
self.each_with_index { |item, index| break item if index =3D=3D n =
}
end
end

Just wondering.

Regards,
Iain
 
P

Paul Harrington

Iain said:
Since hashes in 1.9 retain their insert order, is there a built in way
to get values by index as well as key?

For example:
h = { a: 17, b: 18, c: 19 }

puts h[1]
=> 19

Obviously that can't work, but there may be some other way I haven't
found by looking through the docs? At the moment I'm using this:

class Hash
def by_index( n )
self.each_with_index { |item, index| break item if index == n }
end
end

Just wondering.

Regards,
Iain

I think the closest to what you want is Hash#to_a

Just like
irb(main):011:0> h = Hash[:a, 1, :b, 2, :c, 3]
=> {:a=>1, :b=>2, :c=>3}
irb(main):012:0> h.to_a[0][1]
=> 1
irb(main):013:0>
 
I

Iain Barnett

I think the closest to what you want is Hash#to_a

Just like
irb(main):011:0> h = Hash[:a, 1, :b, 2, :c, 3]
=> {:a=>1, :b=>2, :c=>3}
irb(main):012:0> h.to_a[0][1]
=> 1
irb(main):013:0>

Thanks, I'll see how that pans out.

Regards,
Iain
 
J

Joel VanderWerf

Since hashes in 1.9 retain their insert order, is there a built in way to get values by index as well as key?

For example:
h = { a: 17, b: 18, c: 19 }

puts h[1]
=> 19

Not much better than using #each_with_index or #to_a:
h = { a: 17, b: 18, c: 19 } => {:a=>17, :b=>18, :c=>19}
h[h.keys[1]]
=> 18
 
B

Brian Candler

Iain said:
Since hashes in 1.9 retain their insert order, is there a built in way
to get values by index as well as key?

No - I expect it just keeps them on a global linked list, in addition to
the linked list for each hash bucket.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,769
Messages
2,569,582
Members
45,067
Latest member
HunterTere

Latest Threads

Top