From: pjb@... (Pascal J. Bourguignon) Date: 2009-04-15T01:00:02+09:00 Subject: Re: Argument types Florian Kaufmann writes: > The documentation of the standard classes/methods never mention of > what type/class an argument must be. For example let's look at the > subscript of an Array. There is the form "array[index]". But of what > Type must the index object be? > The ruby book tells me that programming ruby, types doesn't matter so > much, what matters is to what messages an object responds. Thus I > tried the following, thinking that to_i is needed so an object can be > used as an subscript index. Indeed, it would be nice if the arguments "duck type" was documented. > #!/usr/bin/ruby > class C > def to_i > 0 > end > end > c = C.new > a = [0,1,2] > p a[c] > > It doesn't work however: > > ./test:12:in `[]': can't convert C into Integer (TypeError) > from ./test:12 > > So to which messages must C respond so objects of it can be used as > array index? In this case, probably it's not the result of a given method that is used to index the array, but the argument itself! So you are probably expected to give integers as arguments, and no visible message is sent. You would have to check the sources of ruby. But let's make a thought experiment, let's implement Array.at using Memory and Integer: (class Array (def initialize( ... ) (@size = ...) (@addressOfArray = (Memory.allocate @size)) self end) (def addressOf(index) (@addressOfArray + index) end) (def at(index) (if (> 0 index) (index = (@size - index)) end) (if (> 0 index) nil elsif (<= @size index) nil else (Memory.load (self . addressOf index)) end) end) end) Basically, the index should behave as an integer, but in this pseudo-implementation it is not sent any message. It is passed as argument to Integer.+, Integer.-, Integer.>, Integer.<= ; perhaps these methods send some message to the index object, you'd have to check Ruby sources to know. Perhaps they only use the _identity_ of the argument to let the processor compute the result, without sending any message. -- __Pascal Bourguignon__