roger
roger

Reputation: 9913

How can I iterate the first half of a Hash in rails?

I have a Hash such as:

{
    "ruby": 5,
    "python": 4, 
    "java": 3,
    "js": 2,
    "php", 1
}

I know how to iterate the Hash:

<% languages.each for |key, value| %>

<% end %>

I want to iterate the first half part of this Hash, I can get the size of Hash with languages.length, but languages[i] seems return nothing.

Upvotes: 0

Views: 938

Answers (4)

Nafaa Boutefer
Nafaa Boutefer

Reputation: 2359

here is a fast way:

languages.first(languages.length / 2).each do |k, v|
   # Do what ever you want here
end

this is because the hash elements are in the order of which their keys have been inserted.

And to respond to your comment

@Stefan, in fact, i want to get{"ruby": 5, "python": 4, "java": 3} first, then I want to get {"js": 2, "php": 1}

You can use each_slice

 slice_size = 3
 languages.each_slice(slice_size) do |slice|
     slice.each do |key, value|
        # do what you want with each element in the slice
     end
 end

Upvotes: 1

Stefan
Stefan

Reputation: 114228

in fact, i want to get {"ruby": 5, "python": 4, "java": 3} first, then I want to get {"js": 2, "php": 1}

Rails provides a in_groups_of method, but you have to convert languages into an array:

languages = { ruby: 5, python: 4, java: 3, js: 2, php: 1 }.to_a

languages.in_groups_of(3, false).each do |group|
  group.each do |key, value|
    puts "#{key} = #{value}"
  end
  puts '---'
end

Output:

ruby = 5
python = 4
java = 3
---
js = 2
php = 1
---

Upvotes: 3

coderkevin
coderkevin

Reputation: 359

You can get a set of keys:

keys = myhash.keys[0, myhash.length / 2]

Then you can select the hash entries for those keys:

firsthalf = myhash.select {|key,value| keys.include?(key) }

This gives you a copy of the first half of the hash that you can iterate, push to a view to iterate there, etc. However, if this is a really large hash that you don't want to copy, it's best to iterate as above and just stop when you're done.

Upvotes: 1

Stanislav Mekhonoshin
Stanislav Mekhonoshin

Reputation: 4386

You can use each_with_index, it will loop through collection and provider current element index

<% languages.each_with_index for |value, index| %>

<% end %>

Upvotes: 0

Related Questions