`

group_by继续上次的to_proc

阅读更多
Assuming recorded_on is a date, and not a DateTime:

@records = Record.all.group_by(&:recorded_on)

If it is a DateTime:

@records = Record.all.group_by { |record| record.recorded_on.to_date }



让我们看下这一切是如何工作的:

class Symbol     
  # Turns the symbol into a simple proc, which is especially useful for enumerations. Examples:     
  #     
  #   # The same as people.collect { |p| p.name }     
  #   people.collect(&:name)     
  #     
  #   # The same as people.select { |p| p.manager? }.collect { |p| p.salary }     
  #   people.select(&:manager?).collect(&:salary)     
  def to_proc     
    Proc.new { |*args| args.shift.__send__(self, *args) }     
  end     
end    


&符号用在symbol前面实际上是调用了to_proc方法,而to_proc里返回一个Proc对象,内部为调用symbol指定的方法。

这个在ruby IRB和Rails Console有区别如下:
这个是不对的,见下面的更正
irb:
[1, 2, 3, 4, 5,6].group_by{|i| i%2}
return a Hash

rails console:
[1, 2, 3, 4, 5,6].group_by{|i| i%2}
return a Array

rails中支持group_by方法,在console里看看其工作原理:

>> a=(1..20).to_a
=> [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20]
>> a.group_by{|num| num/5}
=> {0=>[1, 2, 3, 4], 1=>[5, 6, 7, 8, 9], 2=>[10, 11, 12, 13, 14], 3=>[15, 16, 17, 18, 19], 4=>[20]}
>>

通过一个block提出的条件将一个数组转化为一个hash.

hash的key是数组元素执行block之后得到的结果
           value是原数组中执行block得到key的元素组成的数组.

所以,可以在rails中这么用:

譬如根据性别对学生进行分组:
@students=Student.find(:all)
@student_groups=@students.group_by{|s| s.gender}
-
那么现在得到的@student_groups就有两组,一组是male,一组是female.
在对其进行循环的时候,使用hash循环的方式:


<% @student_groups.each do |gender,students| %>
<%= gender %>
<ul>
    <% students.each do |student| %>
        <li><%= student.name%></li>
    <% end %>
</ul>
<% end %>

====结果如下:
female
lucy
jessi
male
jack
jim
mike


hash的循环方式:

2层循环,先对keys进行循环,然后是key对应的values进行循环.
分享到:
评论
4 楼 夜鸣猪 2010-07-21  
orcl_zhang 写道
补充上代码
>> [1, 2, 3, 4, 5,6].group_by{|i| i%2} 
=> #<OrderedHash {0=>[2, 4, 6], 1=>[1, 3, 5]}>

Rails 2.3.2

感谢,确实是
3 楼 夜鸣猪 2010-07-21  
是Hash
>> User.all.group_by{|x|x.id}.class
=> ActiveSupport::OrderedHash

2 楼 orcl_zhang 2010-07-21  
补充上代码
>> [1, 2, 3, 4, 5,6].group_by{|i| i%2} 
=> #<OrderedHash {0=>[2, 4, 6], 1=>[1, 3, 5]}>

Rails 2.3.2
1 楼 orcl_zhang 2010-07-21  
irb:
[1, 2, 3, 4, 5,6].group_by{|i| i%2}
return a Hash

rails console:
[1, 2, 3, 4, 5,6].group_by{|i| i%2}
return a Array
===================
你用的什么环境?
rails console的group_by返回也是一个Hash
  def group_by
    assoc = ActiveSupport::OrderedHash.new

    each do |element|
      key = yield(element)

      if assoc.has_key?(key)
        assoc[key] << element
      else
        assoc[key] = [element]
      end
    end

    assoc
  end unless [].respond_to?(:group_by)

相关推荐

Global site tag (gtag.js) - Google Analytics