wroxdb
(wroxdb)
1
Hello,
what's the argument of "obj" in: def []=(index,obj) ?
I don't see it call this method with the second argument.
Thanks
The original code is:
class Array2 < Array
def [](index)
if index>0
super(index-1)
else
raise IndexError
end
end
def []=(index,obj)
if index>0
super(index-1,obj)
else
raise IndexError
end
end
end
x = Array2.new
x[1]=5
x[2]=3
x[0]=1 # Error
x[-1]=1 # Error
Hello,
what's the argument of "obj" in: def =(index,obj) ?
I don't see it call this method with the second argument.
Thanks
The original code is:
class Array2 < Array
def (index)
if index>0
super(index-1)
else
raise IndexError
end
end
def =(index,obj)
if index>0
super(index-1,obj)
else
raise IndexError
end
end
end
x = Array2.new
x[1]=5
This is syntactic sugar for
x.=(1,5)
which is the method you are asking about.
x[2]=3
x[0]=1 # Error
x[-1]=1 # Error
Jesus.
···
On Fri, Nov 5, 2010 at 9:10 AM, wroxdb <wroxdb@gmail.com> wrote:
It's the value on the right of the equals sign:
a[index] = obj
is the same as
a.=(index, obj)
As Jesús pointed out, Ruby supplies syntactic sugar to allow methods
to be called using the syntax of an operator. For example:
5 + 5
is really calling the method "+" on an instance of Fixnum and passing
it the value 5 as an argument:
5.+(5)
Try it in irb:
irb(main):001:0> 5.+(5)
=> 10
irb(main):002:0>
Because operators are really methods, you can define them on your own
classes or override them if needed.
···
On Fri, 5 Nov 2010 03:10:26 -0500, wroxdb <wroxdb@gmail.com> wrote in <AANLkTi=yqFwJvMBi=yZdLj2Rr8rbTQ3pT6tRP8tkCQn1@mail.gmail.com>:
what's the argument of "obj" in: def =(index,obj) ?
--
Charles Calvert | Software Design/Development
Celtic Wolf, Inc. | Project Management
http://www.celticwolf.com/ | Technical Writing
(703) 580-0210 | Research