为什么要在Ruby的某个属性上使用一元运算符?即&amp ;:第一 [英] Why would one use the unary operator on a property in ruby? i.e &:first

查看:96
本文介绍了为什么要在Ruby的某个属性上使用一元运算符?即&amp ;:第一的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可能重复:
Ruby/Ruby on Rails和号冒号快捷方式

Possible Duplicate:
Ruby/Ruby on Rails ampersand colon shortcut

作为一种习惯,我尝试定期阅读一些别人的源代码,并根据要点对它进行评论.现在,我正在阅读sinatra的基本应用程序,并遇到了一些有趣的代码(这是他们的Request类的一部分)

As a habit I try and read a little of someone elses source code regularly and comment on it in a gist. Right now I'm reading through sinatra's base app and came upon an interesting bit of code (this is part of their Request class)

def accept
  @env['sinatra.accept'] ||= begin 
    entries = @env['HTTP_ACCEPT'].to_s.split(',') 
    entries.map { |e| accept_entry(e) }.sort_by(&:last).map(&:first)
  end
end

我不了解的部分是&:last和&:first做的是什么?!?看起来很疯狂!

The part I don't get is what is &:last and &:first doing?!? It appears as madness!

推荐答案

阅读重复问题中有关&:...含义和用法的答案.在这种情况下,entries是一个数组,并且链接了三个方法mapsort_bymap. sort_by(&:last)等同于sort_by{|x| x.last}. map(&:first)map{|x| x.first}相同.第一个map不使用&:...的原因是因为(i)accept_entry的接收者不是e,并且(ii)接受了参数e.

Read the answers in the duplicate questions for the meaning and usage of &:.... In this case, entries is an array, and there are three methods map, sort_by, and map chained. sort_by(&:last) is equivalent to sort_by{|x| x.last}. map(&:first) is the same as map{|x| x.first}. The reason the first map does not use &:... is because (i) the receiver of accept_entry is not e, and (ii) it takes an argument e.

这篇关于为什么要在Ruby的某个属性上使用一元运算符?即&amp ;:第一的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆