问题
I need to hold values in sorted hash in ruby (1.8.7). What data structed will fit the best?
回答1:
There is nothing in the core library or the standard library now, that will fit your bill.
There is, however, a feature request to add a Red/Black-Tree implementation to Ruby 1.9.3/2.0.
If you are able to force your users to only ever use XRuby or JRuby, you could just use one of the implementations of Java's java.util.SortedMap<K, V> such as java.util.TreeMap<K, V>.
If you are able to force your users to only ever use Ruby.NET or IronRuby, you could just use .NET's System.Collections.Generic.SortedDictionary<TKey, TValue>.
If you are able to force your users to only ever use MRI or YARV, you could use the Ruby/RBTree library. It might also work on Rubinius or the not-yet-released JRuby 1.6. Note that there seem to be multiple independent updated forks of that library in the wild. It is not obvious, which one of those is the most recent and/or best maintained one.
The only solution I know of which is guaranteed to be portable, is Kanwei Li's Algorithms and Containers GSoC 2008 project, which actually contains two implementations of a sorted, key-indexed collection: Containers::RBTreeMap based on a Red/Black-Tree and Containers::SplayTreeMap based on a Splay Tree.
回答2:
You might have to roll this yourself, if no one else has a better suggestion.
class SortedHash
def initialize
@data = []
end
def [](k)
@data.find {|kp,vp| kp == k}.last
end
def []=(k, v)
@data.reject! {|kp,vp| kp == k}
@data << [k, v]
@data = @data.sort_by {|kp,vp| kp}
end
def each(&b)
@data.each(&b)
end
end
sh = SortedHash.new
sh[32] = "no"
sh[1] = "later"
sh[99] = "after"
sh.each do |k,v|
p [k,v]
end
Output:
[1, "later"]
[32, "no"]
[99, "after"]
Array is sorted by keys, so they can be of any call and you just need to define comparison operators on them.
回答3:
Use the same class in c# SortedDictionary :
SortedDictionary keyValues = new SortedDictionary();
keyValues.Add(5,"sample5");
keyValues.Add(2, "sample2");
keyValues.Add(6, "sample6");
keyValues.Add(8, "sample8");
keyValues.Add(9, "sample9");
keyValues.Add(1, "sample1");
来源:https://stackoverflow.com/questions/4117139/what-is-ruby-1-8-7-analog-to-sorteddictionary-in-c-net