How would I pass an attribute name to method sort_by, and use it within? For example, say I wanted to create a FrequencyCounter with an array of singleton objects Foo. (It’s important that they’re singletons because it means that there will be a certain number of identical Foos).
class Foo
attr_accessor :arbitrary_sorter
def initialize arbitrary_sorter
@arbitrary_sorter = arbitrary_sorter
end
end
class FrequencyCounter
def initialize ary
#multiset will create a hash of frequency like {3=>obj, 2->obj, 2=>obj, etc}
@hash = Multiset.new(ary).hash
end
def sort_by params={}
Hash[@hash.sort_by {|k,v| [-1 * v, -1 * k]}]
end
end
And when I create Frequency object:
@fc = FrequencyCounter.new([Foo.get(5), Foo.get(4), Foo.get(5), Foo.get(1)])
I’d like to tell @fc what to order on:
@fc.sort_by(:arbitrary_sorter)
Is this possible?
on any enumerator, you can tell it what to sort by. So, let’s take a simple example:
Same as:
You can event do something like:
The lambda may work best for you with the complicated logic I saw.