SitePoint Sponsor

User Tag List

Results 1 to 6 of 6
  1. #1
    SitePoint Member
    Join Date
    Oct 2006
    Posts
    3
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    Getting the first 10 elements of a hash table

    Hey guys,

    I've only recently started with Ruby - so this might well be a very simple, newbie style question - but I haven't managed to find the answer anywhere so far. Here goes then...

    I've got a hash table and I want to be able to print the first 10 elements (it is sorted by value at the moment, so i want to get the "Top Ten" as it were).

    Is there an easy way to do this?

    Cheers,

    Robin

  2. #2
    ☆★☆★ silver trophy vgarcia's Avatar
    Join Date
    Jan 2002
    Location
    in transition
    Posts
    21,235
    Mentioned
    1 Post(s)
    Tagged
    1 Thread(s)
    Code:
    your_hash.first(10).each do |item|
      puts item
    end
    Replace "your_hash" with the name of your hash variable, and change the block to do what you want.

  3. #3
    SitePoint Member
    Join Date
    Oct 2006
    Posts
    3
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Hey,

    Cheers for that reply! Interesting I couldn't seem to find the first method in the class reference at ruby-doc.org. Does it inherit it from some generic object?

    One other thing I'd like to ask, is how do I print out the key and the value from a hash separately. I want to, if possible, print "<key> occured <value> times". How can I access the key separately. Is it something like item.key and item.value?

    Cheers,

    Robin

  4. #4
    SitePoint Guru
    Join Date
    Aug 2005
    Posts
    986
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    you can do it this way:

    Code:
    for key, value in hash
      puts "#{key}: #{value}"
    end

  5. #5
    SitePoint Member
    Join Date
    Oct 2006
    Posts
    3
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Thanks for that - just what I needed

    Robin

  6. #6
    SitePoint Zealot
    Join Date
    Jul 2004
    Location
    Oklahoma
    Posts
    119
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Quote Originally Posted by vgarcia
    Code:
    your_hash.first(10).each do |item|
      puts item
    end
    Replace "your_hash" with the name of your hash variable, and change the block to do what you want.
    Actually, hash doesn't have a "first" method, its only on Array. This makes some sense because a Hash is naturally unordered. You could change that to
    Code:
    your_hash.to_a.first(10).each do |item|
    puts item
    end
    But a Hash by it's nature will not have any order.


Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •