rubycook book:
Recipe 4.7. Making Sure a Sorted Array Stays Sorted
Recipe 4.7. Making Sure a Sorted Array Stays Sorted
class SortedArray < Array
def initialize(*args,&sort_by)
@sort_by = &sort_by || Pro.new{|x,y| x <=> y}
super(*args)
sort! @sort_by
def insert(i,v)
insert_before = index(find{|x| @sort_by.call(x,y) == 1 }
super(insert_before ? insert_before : -1,v)
end
def <<(v)
insert(0,v)
end
alias push <<
alias unshift <<
["collect!", "flatten!", "[]="].each do |method_name|
module_eval %{
def #{method_name}(*args)
super
sort! &@sort_by
end
}
end
def reverse!
#Do nothing; reversing the array would disorder it.
end
end
class
SortedArray
def []=(*args)
if args.size == 3
#e.g. "a[6,3] = [1,2,3]"
start, length, value = args
slice! Range.new(start, start+length, true)
(value.respond_to? :each) ? value.each { |x| self << x } : self << value
elsif args.size == 2
index, value = args
if index.is_a? Numeric
#e.g. "a[0] = 10" (the most common form of array assignment)
delete_at(index)
self << value
elsif index.is_a? Range
#e.g. "a[0..3] = [1,2,3]"
slice! index
(value.respond_to? :each) ? value.each { |x| self << x } : self << value
else
#Not supported. Delegate to superclass; will probably give an error.
super
sort!(&sort_by)
end
else
#Not supported. Delegate to superclass; will probably give an error.
super
sort!(&sort_by)
end
end
end