Skip to content

Instantly share code, notes, and snippets.

@theHamdiz
Last active February 11, 2016 00:16
Show Gist options
  • Select an option

  • Save theHamdiz/2fb104cfe5db56bbd309 to your computer and use it in GitHub Desktop.

Select an option

Save theHamdiz/2fb104cfe5db56bbd309 to your computer and use it in GitHub Desktop.
‪#‎Implement‬ your own sorted list in ‪#‎ruby‬, and how to use predefined SortedSet class.
require 'set'
require 'forwardable'
set = SortedSet.new([8,6,4,2,0,5,9,66,8])
p set # => #<SortedSet: {0, 2, 4, 5, 6, 8, 9, 66}>
# How to implement the same 'SortedSet' functionality on your own
class SortedList
include Enumerable
extend Forwardable
def initialize(data=[])
@data = data.sort!
end
def_delegators :@data, :each, :<<, :push
end
l = SortedList.new([8,6,4,2,0,5,9,66,8])
l << 6 << 7 << 9 << 0 << 5 << 3 << 5 << 66 << 33 << 1
p l
# Go ahead and give it a spin.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment