简体   繁体   English

我如何迭代Hash的前半部分?

[英]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. 我想迭代此Hash的前半部分,我可以使用languages.length获得Hash的大小,但是languages[i]似乎什么也没返回。

in fact, i want to get {"ruby": 5, "python": 4, "java": 3} first, then I want to get {"js": 2, "php": 1} 实际上,我想先获取{"ruby": 5, "python": 4, "java": 3} ,然后再获取{"js": 2, "php": 1}

Rails provides a in_groups_of method, but you have to convert languages into an array: Rails提供了in_groups_of方法,但是您必须将languages转换为数组:

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
---

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. 这为您提供了哈希的前半部分的副本,您可以对其进行迭代,将其推送到视图中进行迭代,等等。但是,如果这是您不想复制的非常大的哈希,则最好将其迭代为在上面,完成后就停下来。

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} @Stefan,实际上,我想先获取{“ ruby​​”:5,“ python”:4,“ java”:3},然后我要获取{“ js”:2,“ php”:1}

You can use each_slice 您可以使用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

You can use each_with_index, it will loop through collection and provider current element index 您可以使用each_with_index,它将遍历集合和提供者当前元素的索引

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

<% end %>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM