On 8/24/06, Morton G. [email protected] wrote:
def array_101
["a", "s", "d"]
0...3 => asd
The only thing I don’t understand is why ‘array_101’ gets added to
Array in irb.
It doesn’t it gets added to the Kernel module, just like in real Ruby.
The difference is that in irb, it’s a public method and in real Ruby
it’s private, I think that this came up in another context in the past
few days.
== file array_101.rb ==
def array_101
for i in [0…self.length]
puts “#{i} => #{self[i]}”
end
end
a = [‘a’, ‘s’, ‘d’]
p a
p a.array_101
class X
end
p X.new.array_101
=== end of file array101.rb===
$ ruby array101.rb
[“a”, “s”, “d”]
array101.rb:9: private method `array_101’ called for [“a”, “s”,
“d”]:Array (NoMethodError)
but change the file to wrap the method in the Kernel module
module Kernel
def array_101
…
end
end
$ ruby array101.rb
[“a”, “s”, “d”]
0…3 => asd
[0…3]
array101.rb:3:in array_101': undefined method
length’ for
#<X:0xb7e1f7b4> (NoMethodError)
from array101.rb:16
Note that we are getting through a.array_101, but now we blow up on
X.new.array_101, but INSIDE the array_101 method, because since it’s
in Kernel, and class Object includes Kernel, makes it available to ALL
objects.
–
Rick DeNatale
My blog on Ruby
http://talklikeaduck.denhaven2.com/
IPMS/USA Region 12 Coordinator
http://ipmsr12.denhaven2.com/
Visit the Project Mercury Wiki Site
http://www.mercuryspacecraft.com/