Can anyone explain the below code?
def sum a,b
yield a,b
end
sum 42, 23, &:+ # <— what does this?
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
While the above worked,why not the below ?
def del a
yield a,‘c’,‘b’
end
del ‘abcd’, &:delete
The second example is correct as well, as it is equivalent to
‘abcd’.delete(‘a’, ‘b’)
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
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.
This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.
Sponsor our Newsletter | Privacy Policy | Terms of Service | Remote Ruby Jobs