Last active
February 11, 2016 00:16
-
-
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.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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