&rubram方法中的&param和:&param之间的区别

时间:2022-04-15 22:27:41

I have functions with the definition def test(&param) and def test(:&param). What is the difference between both?

我有定义def测试(&param)和def测试(:&param)的函数。两者有什么区别?

2 个解决方案

#1


4  

def test(&block) ...

means that our method accepts a block:

意味着我们的方法接受一个块:

def test(number, &block)
  yield number
  # same as
  # block.call number
end
test(10) {|a| a+a}
#=> 20
# or
block = proc{|a| a*a}
test 10, &block
#=> 100

While def test(:&param) will throw an error.

虽然def测试(:&param)会抛出错误。

Also you can call something like method(&:operator):

你也可以调用方法(&:operator):

[1,2,3].inject(&:+)
#=> 6

That is the same as

那是一样的

[1,2,3].inject{|sum, i| sum+i }

#2


6  

The difference is that def test(:&param) causes a syntax error and def test(&param) does not.

区别在于def测试(:&param)导致语法错误,而def测试(&param)则没有。

#1


4  

def test(&block) ...

means that our method accepts a block:

意味着我们的方法接受一个块:

def test(number, &block)
  yield number
  # same as
  # block.call number
end
test(10) {|a| a+a}
#=> 20
# or
block = proc{|a| a*a}
test 10, &block
#=> 100

While def test(:&param) will throw an error.

虽然def测试(:&param)会抛出错误。

Also you can call something like method(&:operator):

你也可以调用方法(&:operator):

[1,2,3].inject(&:+)
#=> 6

That is the same as

那是一样的

[1,2,3].inject{|sum, i| sum+i }

#2


6  

The difference is that def test(:&param) causes a syntax error and def test(&param) does not.

区别在于def测试(:&param)导致语法错误,而def测试(&param)则没有。