简体   繁体   中英

ruby when we are passing more than 4 value in set how it arrange that value in set

 Set.new

=> #<Set: {}>

irb(main):003:0> Set[1,2,3,4,5,6]

=> #<Set: {5, 6, 1, 2, 3, 4}>

irb(main):004:0> Set[1,2,3,4,5,6,7,8,9,10,11,12,13,14,15]

=> #<Set: {5, 11, 6, 12, 1, 7, 13, 2, 8, 14, 3, 9, 15, 4, 10}>

irb(main):005:0> Set[1,2,3,4,5,6,7,8,9,10]

=> #<Set: {5, 6, 1, 7, 2, 8, 3, 9, 4, 10}>

irb(main):006:0> Set[1,2,3,4,5]

=> #<Set: {5, 1, 2, 3, 4}>

irb(main):007:0> Set[1,2,3,4]

=> #<Set: {1, 2, 3, 4}>

irb(main):008:0> Set[1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20]

=> #<Set: {16, 5, 11, 17, 6, 12, 1, 18, 7, 13, 2, 19, 8, 14, 3, 20, 9, 15, 4, 10}>

irb(main):009:0> Set[1,2,4,5,3,7]

=> #<Set: {5, 1, 7, 2, 3, 4}>

I want to know which algorithm Ruby is using to enter value in sets

http://www.ruby-doc.org/stdlib-1.9.3/libdoc/set/rdoc/SortedSet.html SortedSet实现了一个Set,保证它的元素按排序顺序生成

You've said "in language nothing is generated without order" but that isn't true. Hashes are generated without order.

In Ruby 1.9, though, additional infrastructure has been added on top of hashes to give them an insertion order that is used when iterating (meaning that even though they are stored unordered, they essentially maintain a linked list they can use when being traversed). Since sets are implemented with hashes, they will be unordered in 1.8 and ordered in 1.9 , but you should not rely on this order (otherwise it's not a set, it's a list -- array in Ruby speak).

Here is a simple example of implementing a hash.

This article discusses how the ordering is added.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM