为了账号安全,请及时绑定邮箱和手机立即绑定

Ruby符号和冒号快捷方式

Ruby符号和冒号快捷方式

蓝山帝景 2019-06-14 17:22:53
Ruby符号和冒号快捷方式在Ruby中,我知道如果我这么做了:some_objects.each(&:foo)就像some_objects.each { |obj| obj.foo }那是,&:foo创建块{ |obj| obj.foo }将其转化为程序,并将其传递给每个人。为什么这样做?这仅仅是Ruby的一个特例,还是有理由这样做呢?
查看完整描述

2 回答

?
呼如林

TA贡献1798条经验 获得超3个赞

符号和符号的结合没有什么特别之处。下面是一个(Ab)使用正则表达式的示例:

class Regexp
  def to_proc    ->(str) { self =~ str ; $1 }
  endend%w(station nation information).map &/(.*)ion/=> ["stat", "nat", "informat"]

或者整数。

class Integer
  def to_proc    ->(arr) { arr[self] }
  endendarr = [[*3..7],[*14..27],[*?a..?z]]arr.map &4=> [7, 18, "e"]

谁需要arr.map(&:fifth)当你有arr.map &4?


查看完整回答
反对 回复 2019-06-14
  • 2 回答
  • 0 关注
  • 612 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信