
Weird Ruby: Positive and Negative Strings - lelf
https://metaredux.com/posts/2019/05/10/weird-ruby-positive-and-negative-strings.html
======
kentor
Mutable strings was a mistake.

------
woodruffw
The more general takeaway from this is that you can redefine (some of) Ruby's
unary operators. Their naming is unfortunately less consistent than Python's
dunder-methods, but each of these work: `+@` for `+`, `-@` for `-`, `~` for
`~`.

Edit: Removed incorrect information.

~~~
vidarh
'to_a' and * are not at all the same, and neither are 'to_proc' and '&'

unary * is the splat operator. While it tries to coerce arguments to an array,
consider that this:

    
    
      x,y,z = *(1..3),42
    

gives x=1,y=2,z=3, while:

    
    
      x,y,z = (1..3).to_a, 42
    
      gives x=[1,2,3], y=42, z= nil
    

'&' meanwhile _passes a Proc_ as the anonymous block to a method. E.g.:

    
    
      def foo; yield; end
      pr = proc { puts "here" }
      foo(&pr) # is equivalent to foo { puts "here" }
    

It too will _try_ to coerce arguments to a proc by calling '#to_proc' on
objects that responds to it, but 'to_proc' just returns a Proc (or should), it
does not in itself convert a Proc to a default block. 'to_proc' has other uses
- proc's can be passed around in all kinds of other situations too.

~~~
woodruffw
Yeah, I misremembered. Ruby does indeed complain when either `to_proc` or
`to_a` don't return the expected types.

