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)
@
[email protected]_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进行循环.