rubycook book:
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
分享到:
相关推荐
PySimpleGUI cookbook-zh-CN 中文版 非机器翻译(目录标题未翻译)
Boost C++ Application Development Cookbook - Second Edition
coverage-cookbook-complete-verification-academy Candence Academy官方coverage文档
python-machine-learning-cookbook-preprocessing oreilly 英文 epub格式
Modern-CPP-Programming-Cookbook-Second-Edition-master Packt 出版 仅供学习参考,阅后删除。
Programming ArcGIS with Python Cookbook - Second Edition, mobi格式
Programming ArcGIS with Python Cookbook - Second Edition,epub格式
docker run -tid -p <port>:80 apachecn0/pandas-cookbook-code-notes # 访问 http://localhost:{port} 查看文档 PYPI pip install pandas-cookbook-code-notes pandas-cookbook-code-notes # 访问 ...
nginx-cookbook-recipes-high-performance
Unity Game Development Cookbook - Paris Buttfield-AddisonUnity Game Development Cookbook - Paris Buttfield-Addison
Linux Shell Scripting Cookbook - Third Edition by Clif Flynt English | 29 May 2017 | ASIN: B01N80F75Z | 552 Pages | AZW3 | 1.36 MB Do amazing things with the shell About This Book Become an expert ...
uvm-cookbook-registers-guide-verification-academy
KVM实操手册, 英语简练易懂, 讲的面比较全, KVM的相关内容基本都涉及到了, 内容全面,可操作性强.
uvm-cookbook-complete-verification-academy
pandas学习手册
modern-cpp-programming-cookbook-2nd
Kali Linux Cookbook - Second Edition.mobi Kali Linux Cookbook - Second Edition.mobi
Kali Linux Cookbook - Second Edition.epub Kali Linux Cookbook - Second Edition.epub