Not being able to understand ruby code

Can anyone explain the below code?

def sum a,b
yield a,b
end
sum 42, 23, &:+ # <— what does this?

The last line is equivalent to
sum(42, 23) { |a, b| a + b }

The & operator turns the operator referred to by the :+ symbol into a
Proc.

Andrew B. wrote in post #1126301:

The last line is equivalent to
sum(42, 23) { |a, b| a + b }

The & operator turns the operator referred to by the :+ symbol into a
Proc.

This is interesting… I am trying to understand… How should I catch
such format for other cases…Here is some try :

def del a
yield a,‘c’
end
del ‘abcd’, &:delete

=> “abd”

While the above worked,why not the below ?

def del a
yield a,‘c’,‘b’
end
del ‘abcd’, &:delete

=> “abcd”

The second example is correct as well, as it is equivalent to
‘abcd’.delete(‘a’, ‘b’)

=> “abcd”

The documentation of String#delete says that it “Returns a copy of str
with all characters in the intersection of its arguments deleted.”
The intersection of ‘a’ and ‘b’ is an empty set.

Love U Ruby wrote in post #1126304:

Andrew B. wrote in post #1126301:

While the above worked,why not the below ?

def del a
yield a,‘c’,‘b’
end
del ‘abcd’, &:delete

=> “abcd”

got it from
http://www.ruby-doc.org/core-2.0.0/String.html#method-i-delete

Returns a copy of str with all characters in the intersection of its
arguments
deleted.

Returns a copy of str with all characters in the intersection of its
arguments
deleted.

My reply was a bit too late. :wink:

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs