Rahul
Rahul

Reputation: 47146

Difference between &param and :&param in ruby methods

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

Upvotes: 0

Views: 244

Answers (2)

fl00r
fl00r

Reputation: 83680

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.

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

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

That is the same as

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

Upvotes: 4

sepp2k
sepp2k

Reputation: 370455

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

Upvotes: 6

Related Questions