Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get first n elements from Hash in ruby?

Tags:

ruby

I have a Hash and i have sorted it using the values

@friends_comment_count.sort_by{|k,v| -v}

Now i only want to get hash of top five elements .. One way is to use a counter and break when its 5. What is preferred way to do in ruby ?

Thanks

like image 879
harshit Avatar asked Dec 20 '11 18:12

harshit


People also ask

How do I get the hash value in Ruby?

In Ruby, a hash is a collection of key-value pairs. A hash is denoted by a set of curly braces ( {} ) which contains key-value pairs separated by commas. Each value is assigned to a key using a hash rocket ( => ). Calling the hash followed by a key name within brackets grabs the value associated with that key.

Can you sort a hash in Ruby?

Sorting Hashes in RubyTo sort a hash in Ruby without using custom algorithms, we will use two sorting methods: the sort and sort_by. Using the built-in methods, we can sort the values in a hash by various parameters.

Do hashes have indexes Ruby?

A Hash is a collection of key-value pairs. It is similar to an Array , except that indexing is done via arbitrary keys of any object type, not an integer index.

Can a hash have multiple values Ruby?

Each key can only have one value. But the same value can occur more than once inside a Hash, while each key can occur only once.


2 Answers

h = { 'a' => 10, 'b' => 20, 'c' => 30 }

# get the first two
p Hash[*h.sort_by { |k,v| -v }[0..1].flatten]

EDITED:

# get the first two (more concisely)
p Hash[h.sort_by { |k,v| -v }[0..1]]
like image 91
Marek Příhoda Avatar answered Sep 26 '22 12:09

Marek Příhoda


Can't you just do something like:

h = {"test"=>"1", "test2"=>"2", "test3"=>"3"}

Then if you wanted the first 2:

p h.first(2).to_h

Result:

=> {"test"=>"1", "test2"=>"2"}
like image 26
Trinculo Avatar answered Sep 26 '22 12:09

Trinculo