Velocity Reviews - Computer Hardware Reviews

Velocity Reviews > Newsgroups > Programming > Ruby > efficient way to get the first found (or a random) key/value of a large hash

Reply
Thread Tools

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

 
 
David Garamond
Guest
Posts: n/a
 
      01-12-2004
# 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}

--
dave


 
Reply With Quote
 
 
 
 
Hal Fulton
Guest
Posts: n/a
 
      01-12-2004
David Garamond wrote:
> # 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






 
Reply With Quote
 
 
 
 
Ville Aine
Guest
Posts: n/a
 
      01-13-2004
David Garamond <lists@zara.6.isreserved.com> wrote in message news:<40025921.4090603@zara.6.isreserved.com>...

> # 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]]
 
Reply With Quote
 
Emmanuel Touzery
Guest
Posts: n/a
 
      01-14-2004
Ville Aine wrote:

>David Garamond <lists@zara.6.isreserved.com> wrote in message news:<40025921.4090603@zara.6.isreserved.com>...
>
>
>># 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.



 
Reply With Quote
 
 
 
Reply

Thread Tools

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Trackbacks are On
Pingbacks are On
Refbacks are Off


Similar Threads
Thread Thread Starter Forum Replies Last Post
Memory efficient way to store strings in hash maps using 朝の木 C++ 3 04-18-2012 09:37 AM
hash of hash of hash of hash in c++ rp C++ 1 11-10-2011 04:45 PM
Most efficient way to access a large member struct from another class Angus C++ 6 01-05-2010 10:46 PM
An efficient way to make a large directory tree? Nan Wang Perl Misc 8 12-04-2004 11:01 AM
Re: I have found a efficient way to flirt... kpg MCSE 0 07-30-2004 04:43 PM



Advertisments