Class: SortedArray::DefaultSorter

Inherits:
Object
  • Object
show all
Defined in:
lib/sorted_array/default_sorter.rb

Overview

Sorts by comparing of :field a <=> b.

Descend your Sorter from this class. It must at least define a method 'sort'.

Examples:

class Foo
  def initialize(_bar)
    @bar = _bar
  end
  def bar
    @bar
  end
end
s = DefaultSorter.new(:bar)
a = SortedArray(s, Foo.new(1), Foo.new(3), Foo.new(2))
# => Foo(1), Foo(2), Foo(3)

See Also:

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(_method) ⇒ DefaultSorter

Returns a new instance of DefaultSorter.

Parameters:

  • _method (String)
    • the method to be used while sorting.


25
26
27
# File 'lib/sorted_array/default_sorter.rb', line 25

def initialize(_method)
  @method = _method
end

Instance Attribute Details

#methodObject (readonly)

Returns the value of attribute method.



22
23
24
# File 'lib/sorted_array/default_sorter.rb', line 22

def method
  @method
end

Instance Method Details

#marshal_dumpArray

Returns - Classname, methodname.

Returns:

  • (Array)
    • Classname, methodname


39
40
41
# File 'lib/sorted_array/default_sorter.rb', line 39

def marshal_dump
  [ self.class, @method ]
end

#marshal_load(array) ⇒ Object

Parameters:

  • array (Array)
    • _classname,[..entries..]


44
45
46
# File 'lib/sorted_array/default_sorter.rb', line 44

def marshal_load array
  @method = array.last
end

#sort(object) ⇒ Object

This method is abstract.

Overwrite this method in descendants

Sort the given object. to sort your objects for your needs

Parameters:

  • what (Object)
    • what must provice a method sort! and :method

Returns:

  • (Object)


34
35
36
# File 'lib/sorted_array/default_sorter.rb', line 34

def sort(object)
  object.sort! { |a,b| a.send(@method) <=> b.send(@method) }
end