Forum: Ruby Not being able to understand ruby code

249c7fd851c5c5ac5a1abdb756472ae1?d=identicon&s=25 Arup Rakshit (my-ruby)
on 2013-11-02 06:11
Can anyone explain the below code?

def sum a,b
  yield a,b
end
sum 42, 23, &:+  # <--- what does this?
6cd5090839b1021f85bd329e1ed09264?d=identicon&s=25 Andrew B. (andrew_b19)
on 2013-11-02 09:09
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.
249c7fd851c5c5ac5a1abdb756472ae1?d=identicon&s=25 Arup Rakshit (my-ruby)
on 2013-11-02 09:42
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"
249c7fd851c5c5ac5a1abdb756472ae1?d=identicon&s=25 Arup Rakshit (my-ruby)
on 2013-11-02 09:51
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#met...

Returns a copy of str with all characters in the **intersection of its
arguments** deleted.
6cd5090839b1021f85bd329e1ed09264?d=identicon&s=25 Andrew B. (andrew_b19)
on 2013-11-02 09:57
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.
6cd5090839b1021f85bd329e1ed09264?d=identicon&s=25 Andrew B. (andrew_b19)
on 2013-11-02 09:59
> Returns a copy of str with all characters in the **intersection of its
> arguments** deleted.

My reply was a bit too late. ;)
Please log in before posting. Registration is free and takes only a minute.
Existing account

NEW: Do you have a Google/GoogleMail, Yahoo or Facebook account? No registration required!
Log in with Google account | Log in with Yahoo account | Log in with Facebook account
No account? Register here.