This example demonstrates how Dynarex records can be sorted in-place:

require 'dynarex'

lines =<malcolm 45
Stuart 44
Mary 46
Richard 43
LINES

scores = Dynarex.new('scores/player(name,score)').parse lines

puts scores.to_xml





dynarex
[!name] [!score]
scores/player(name,score)



malcolm
45


Stuart
44


Mary
46


Richard
43





Here's how it should look from the client's view:

scores.sort_by {|player| player.score}
# or
scores.sort_by! {|player| player.score} # to make it permanent


Here's basically how it will work internally:

doc = Document.new scores.to_xml
a = XPath.match(doc.root, 'records/player').sort_by {|x| x.text('score').to_i}
puts a.map{|x| "%+7s: %s" % %w(name score).map {|f| x.text(f)}}

output:

Richard: 43
Stuart: 44
malcolm: 45
Mary: 46



records = XPath.first(doc.root, 'records')
records.parent.delete records
records = Element.new 'records'
a.each {|record| records.add record}
doc.root.add records
puts doc.to_s

output:




dynarex
[!name] [!score]
scores/player(name,score)



Richard
43

Stuart
44

malcolm
45

Mary
46



Read more: http://feeds.dzone.com/~r/dzone/snippets/~3/4Nz8p1-p0sU/11595