4 ms·
Weird Ruby: Positive and Negative Strings
- woodruffw 7y agoThe 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 7y ago'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 7y agoYeah, I misremembered. Ruby does indeed complain when either `to_proc` or `to_a` don't return the expected types.
- kentor 7y agoMutable strings was a mistake.