我刚刚完成了一个关于ruby的课程,其中教师将电影列表分组,然后对它们进行分组,然后调用map,sort和reverse。它工作正常,但我没有发现语法是非常可读的,我试图弄清楚我脑海中是否有效。我来自c#背景。以一种干净的方式链接ruby枚举器函数
#we can reformat our code to make it shorter
#note that a lot of people don't like calling functions on the
#end of function blocks. (I don't like the look, either)
count_by_month = movies.group_by do |movie|
movie.release_date.strftime("%B")
end.map do |month, list|
[month, list.size]
end.sort_by(&:last).reverse
我想知道是,如果我可以这样做
#my question: can I do this?
count_by_month = movies.group_by(&:release_date.strftime("%B"))
.map(&:first, &:last.size)
.sort_by(&:last)
.reverse
#based on what I've seen online, I could maybe do something like
count_by_month = movies.groupBy({m -> m.release_date.strftime("%B")})
.map{|month, list| [month, list.size]}
.sort_by(&:last)
.reverse
这真的是一种风格的东西,但大多数情况下,单行使用'{}'块语法,多行使用'do'' end' - 以下是一些使用的样式指南:https://github.com/styleguide/ruby。这当然是codereview的问题,虽然不是SO – Anthony 2015-02-05 22:26:14
不,你不能[发布其他人的代码](http://meta.codereview.stackexchange.com/questions/3649/my-question-was-closed-as-being -off-topic-what-are-my-options/3654#3654)。 – Hosch250 2015-02-05 22:28:08
如果你的逻辑块不是单线,那么你可以使用lambdas:'release_date = lambda {| movie | ...}; movies.group_by(&RELEASE_DATE).MAP(....)'。 – 2015-02-05 22:37:00