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.
`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
maybe it depends on browser? and still doesn't work – Tomasz Drgas Dec 06 '18 at 10:15