&:aFunction 的 &: 是做什么的? [英] What is the &: of &:aFunction doing?

查看:55
本文介绍了&:aFunction 的 &: 是做什么的?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在审查某人的 ruby​​ 代码,他们在其中编写了类似于以下内容的内容:

I'm reviewing someone's ruby code and in it they've written something similar to:

class Example
  attr_reader :val
  def initialize(val)
    @val = val
  end
end

def trigger
  puts self.val
end

anArray = [Example.new(10), Example.new(21)]
anArray.each(&:trigger)

:trigger 表示采用符号,& 将其转换为 proc?

The :trigger means the symbol is taken and the & transforms it into a proc?

如果这是正确的,除了使用 self. 之外,还有什么方法可以将变量传递给触发器吗?

If that's correct, is there any way of passing variables into trigger apart from using self.?

这是相关的但从未回答过:http://www.ruby-forum.com/topic/198284#863450

This is related but never answered: http://www.ruby-forum.com/topic/198284#863450

推荐答案

有没有办法将变量传递给触发器

is there any way of passing variables into trigger

没有

您正在调用不允许您指定任何参数的 Symbol#to_proc.这是 Ruby 专门为调用不带参数的方法提供的便利.

You're invoking Symbol#to_proc which does not allow you to specify any arguments. This is a convenient bit of sugar Ruby provides specifically for invoking a method with no arguments.

如果需要参数,则必须使用完整的块语法:

If you want arguments, you'll have to use the full block syntax:

anArray.each do |i|
  i.trigger(arguments...)
end

这篇关于&:aFunction 的 &: 是做什么的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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