3 ms·
Ruby overuses []. It is used in Array literals, but it is also an operator (i.e. a method with odd syntax) on several classes: Array, String, Fixnum, Bignum, P
by cgrubb 16y ago
Ruby overuses []. It is used in Array literals, but it is also an operator (i.e. a method with odd syntax) on several classes: Array, String, Fixnum, Bignum, Proc. In a language with dynamic typing, we should avoid having methods (or operators) with the same name and different function since calling nonexistent methods is how we catch errors.
The [] operator on Proc was new to me. I don't like the [] on Fixnum and Bignum, which is a bit operation: x[y] := (x << y) & 1. Hence my fixes to Ruby would be:
$ irb
001> add = lambda {|x,y| x+y}
=> #<Proc:0x0000010089ef30@(irb):1 (lambda)>
002> add[1,2]
=> 3
003> 1[2]
=> 0
004> class Proc; undef_method :[]; end
=> Proc
005> class Fixnum; undef_method :[]; end
=> Fixnum
006> class Bignum; undef_method :[]; end
=> Bignum
007> add[1,2]
NoMethodError: undefined method `[]' for #<Proc:0x0000010089ef30@(irb):1 (lambda)>
from (irb):7
from /usr/local/bin/irb:12:in `<main>'
008> 1[2]
NoMethodError: undefined method `[]' for 1:Fixnum
from (irb):8
from /usr/local/bin/irb:12:in `<main>'
009> (100**100)[1]
NoMethodError: undefined method `[]' for #<Bignum:0x00000101116f50>
from (irb):9
from /usr/local/bin/irb:12:in `<main>'
I'm also tempted to remove [] from String, but the usefulness probably outweighs the occasional confusion from thinking a String is an Array.