Incidentally, you can make your class more general-purpose by using ===,
noting that klass1 === obj is true if obj.is_a?(klass1)
i.e.
case obj
when klass1
# this is executed if klass1 === obj
end
I’m not sure exactly what you’d call it (I seem to remember this naming
problem occured for Test::Unit as well), but you’d have something like:
module ArrayMisc
def shift_until_match(caseitem)
res = []
loop do
break if caseitem === self.first
res << self.shift
end
res
end
end
Then you can do:
class Array; include ArrayMisc; end
a = [0,1,“two”,“three”,“four”,“five”]
b = a.shift_until_match(String)
p a,b
#>> [“two”, “three”, “four”, “five”] [0, 1]
b = a.shift_until_match(/^f/)
p a,b
#>> [“four”, “five”] [“two”, “three”]
Regards,
Brian.
Oops, infinite loop if no match! Should be:
break if length == 0 or caseitem === first
Cheers,
Brian.
···
On Thu, May 29, 2003 at 05:35:05PM +0900, Brian Candler wrote:
break if caseitem === self.first
Thanks… Brian you have lead me to the solution.
My problem was that ‘Array.extend ArrayMisc’ was located in
a method-scope. Moving the following piece of code out into the
global scope, then everything works.
#Array.extend ArrayMisc
class Array; include ArrayMisc; end
AFAIK. I should be able to do an ‘Array.extend’ as above.
But it does not work. Why ?
What is the difference between these 2 lines ?
···
–
Simon Strandgaard
a = Array.new – a is an instance of Array
a.extend ArrayMisc – adds the methods of ArrayMisc into a’s singleton
class (i.e. they become instance methods of ‘a’)
class Array
include ArrayMisc – adds the methods of ArrayMisc as instance methods
of the class Array
end
Now, class Array does have a singleton class, but it’s not what you want
to add your method into. The singleton class of a Class is where the ‘class
methods’ go:
module Foo
def foo
puts “hello”
end
end
Array.extend Foo # puts methods of Foo into singleton class of Array
Array.foo
#>> “hello”
In other words, you have created a method which belongs to class Array, not
which belongs to instances of class Array.
Hope this makes sense… there are several pages about this on the wiki,
including http://www.rubygarden.org/ruby?SingletonTutorial
Regards,
Brian.
···
On Thu, May 29, 2003 at 07:20:00PM +0900, Simon Strandgaard wrote:
Thanks… Brian you have lead me to the solution.
My problem was that ‘Array.extend ArrayMisc’ was located in
a method-scope. Moving the following piece of code out into the
global scope, then everything works.
#Array.extend ArrayMisc
class Array; include ArrayMisc; end
AFAIK. I should be able to do an ‘Array.extend’ as above.
But it does not work. Why ?
What is the difference between these 2 lines ?
OK… I see. I wasn’t aware of this. Now I ‘think’ I understand
BTW: the case equality trick you showed me is really nice.
···
On Thu, 29 May 2003 20:34:54 +0900, Brian Candler wrote:
In other words, you have created a method which belongs to class Array, not
which belongs to instances of class Array.
–
Simon Strandgaard