the second argument

W

wroxdb

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
 
J

Jesús Gabriel y Galán

Hello,

what's the argument of "obj" in: =A0 def []=3D(index,obj) ?

I don't see it call this method with the second argument.
Thanks


The original code is:

class Array2 < Array

=A0def [](index)
=A0 =A0if index>0
=A0 =A0 =A0super(index-1)
=A0 =A0else
=A0 =A0 =A0raise IndexError
=A0 =A0end
=A0end

=A0def []=3D(index,obj)
=A0 =A0if index>0
=A0 =A0 =A0super(index-1,obj)
=A0 =A0else
=A0 =A0 =A0raise IndexError
=A0 =A0end
=A0end

end


x =3D Array2.new

x[1]=3D5

This is syntactic sugar for

x.[]=3D(1,5)

which is the method you are asking about.
x[2]=3D3
x[0]=3D1 # Error
x[-1]=3D1 # Error

Jesus.
 
C

Charles Calvert

what's the argument of "obj" in: def []=(index,obj) ?

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.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
474,142
Messages
2,570,819
Members
47,367
Latest member
mahdiharooniir

Latest Threads

Top