ruby - How does this code with send :[] work? -
the following code generates output of 9. understand send
calling method :[]
, confused how parameters work.
x = [1,2,3] x.send :[]=,0,4 #why x [4,2,3] x[0] + x.[](1) + x.send(:[],2) # 4 + 2 + 3
how line 2 , line 3 work?
line 2 is
x.send :[]=,0,4
that fancy way of writing this:
x[0] = 4
(calling send
allows call private methods though, , 1 difference between 2 syntaxes. also, object conceivably override send
method, break first syntax.)
so line 2 has effect of writing 4 first spot in array.
now on line 3, see adding 3 things. here list of things adding:
x[0]
- first elementx.[](1)
- syntax accessing elements, accesses second element. syntax traditional method call, name of method happens[]
.x.send(:[], 2)
- shows feature of ruby,send
method. accesses third element.
so result 9, because third line adds first, second, , third elements of array.
these examples appear illustrate interesting point design of ruby language. specifically, array accesses implemented method calls. preferred syntax writing array x[0] = 4
, preferred syntax reading x[0]
, because syntax familiar programmers many different languages. however, reading , writing arrays implemented using method calls under hood, , that's why possible use other syntaxes more traditional method call.
a traditional method call looks this: object.foo(arg1, arg2, arg3, ...)
.
the send
thing shown above useful feature of ruby allows specify method calling using symbol, instead of forcing type exact name. lets call private methods.
Comments
Post a Comment