1

I've seen an example of how to sort a string. To sort case insensitively:

str.chars.sort(&:casecmp).join
#=> "ginrSt"

I'm curious about (&:casecmp). I found that for example:

arr.map(&:name)

is shorthand for

arr.map(&:name.to_proc)

which is same with

arr.map{|el| el.name}

I know the & (ampersand) tries to convert symbol to proc, and pass it as a block to a method. I do not understand how this would work for sort method, which is supposed to compare two values. Would it be as follows?

str.chars.sort{|a, b| a.casecmp ;b.casecmp}.join

It wouldn't be helpful since soft needs a block to return an integer and casecmp needs an argument. (Or is it called parameter in that case?) To me, it looks more like this:

str.chars.sort{|a, b| a.casecmp(b)}.join

How does &:casecmp know to take one of |a, b| as a caller and the other one as an argument? I wouldn't guess it that it is an option.

sawa
  • 165,429
  • 45
  • 277
  • 381
  • 1
    Also: http://symbolhound.com/?q=ruby+%26%3A – mu is too short Dec 05 '18 at 05:59
  • Ok I found this:
    `class Symbol def to_proc Proc.new do |obj, *args| obj.send self, *args end end end` this I guess why the second parameter from __|a, b|__ was taken as an argument.. still feel anfamiliar with &:symb but reading about that..
    I did try to add two spaces and
    to make line break.. when pressing enter automaticly addscomment.. don't know how to do it
    – Tomasz Drgas Dec 05 '18 at 06:12
  • @mu is to short .. I was reading the help about comments formating, but nowhere I have seen anything about you must press Shift + Enter for linebreak which I overuse now..
    maybe it depends on browser? and still doesn't work
    – Tomasz Drgas Dec 06 '18 at 10:15

1 Answers1

1

If more than one parameter is passed to your block, the proc created by Symbol#to_proc uses the additional block parameters as parameters to the method call.

http://phrogz.net/symbol-to-proc-with-multiple-arguments

So, what's really happening is, sort(&:casecmp) is converted to:

sort {|a,b| a.casecmp(b) }

because sort takes two parameters.

Raj
  • 22,346
  • 14
  • 99
  • 142
  • Thanks @emaillenin... how do you do line breakes .. when I do 2 spaces on the end and hit enter it adds a coment.. – Tomasz Drgas Dec 05 '18 at 07:10
  • @Tomasz use shift + enter – Raj Dec 05 '18 at 09:19
  • one more time .. THANKS I didn't see anything about Shift + Enter when reading about formating comments but it work in the comment editing window only.. there is no linebreak after saving it and
    doesn't help
    – Tomasz Drgas Dec 06 '18 at 10:19