efficient way to get the first found (or a random) key/value of a large hash

D

David Garamond

# a large hash
h = { ... }

# 1. this is inefficient
first_key, first_value = h.keys[0], h.values[0]

# also, #1 is not thread-safe right?
# is there a #pairs method which returns [[k1,v1], [k2,v2], ...} or
# something similar?

# 2. will this be compatible with future ruby?
h.each_pair {|k,v| first_key, first_value = k, v; break}
 
H

Hal Fulton

David said:
# a large hash
h = { ... }

# 1. this is inefficient
first_key, first_value = h.keys[0], h.values[0]

# also, #1 is not thread-safe right?
# is there a #pairs method which returns [[k1,v1], [k2,v2], ...} or
# something similar?

# 2. will this be compatible with future ruby?
h.each_pair {|k,v| first_key, first_value = k, v; break}


Hmm, how about:

k,v = h.find { true } # Find first obj for which block is true


Hal
 
V

Ville Aine

David Garamond said:
# is there a #pairs method which returns [[k1,v1], [k2,v2], ...} or
# something similar?

Hash#to_a does just that:

irb(main):003:0> {:a => 1, :b => 2}.to_a
=> [[:a, 1], [:b, 2]]
 
E

Emmanuel Touzery

Ville said:
# is there a #pairs method which returns [[k1,v1], [k2,v2], ...} or
# something similar?
Hash#to_a does just that:

irb(main):003:0> {:a => 1, :b => 2}.to_a
=> [[:a, 1], [:b, 2]]
yes, but converting the whole hash to an array is inefficient (for big
hashes), that's why he doesn't want to use this.
 

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,969
Messages
2,570,161
Members
46,705
Latest member
Stefkari24

Latest Threads

Top