Morton Goldberg
8/25/2006 1:39:00 AM
Your code only works in irb. You get an error, as you should, if you
run it 'real' Ruby.
In irb 'array_101' gets added to Array. That's the only reason
'a.array_101' doesn't produce an error. In "real" Ruby, the following
produces your result, as it should.
<code>
#! /usr/bin/ruby -w
class Array
def array_101
for i in [0...length]
p self[i] ### prints the array because i = 0...length, not 0.
puts "#{i} => #{self[i]}"
end
end
end
a = %w[a s d]
a.array_101
</code>
<result>
["a", "s", "d"]
0...3 => asd
</result>
The only thing I don't understand is why 'array_101' gets added to
Array in irb.
Regards, Morton
On Aug 24, 2006, at 12:57 PM, Henry Savr wrote:
> Well, you wrote a great Array Analyzer
> Here it is:
>
> def array_101
> for i in [0 ... self.length]
> puts "#{i} => #{self[i]}"
> end
> end
>
> And prepared the following array for test:
>
> a = ['a','s','d']
>
> What do you think, it will print?
>
> Yeeees, you are right.
> And the answer is...
>
> 0...3 => asd
>
> :-)))))))))
>
> try it at home:
>
> irb(main):001:0> def array_101
> irb(main):002:1> for i in [0 ... self.length]
> irb(main):003:2> puts "#{i} => #{self[i]}"
> irb(main):004:2> end
> irb(main):005:1> end
> => nil
> irb(main):006:0> a = ['a','s','d']
> => ["a", "s", "d"]
> irb(main):007:0> a.array_101
> 0...3 => asd
> => [0...3]
> ;-)