Advertisement
Guest User

Untitled

a guest
Oct 14th, 2019
101
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.96 KB | None | 0 0
  1. module IterationsSugar
  2.  
  3. def extract
  4. result = ActiveArray.new
  5. each_with_index do |item, index|
  6. e = yield item, index
  7. result << e unless e.nil?
  8. end
  9. result
  10. end
  11.  
  12. def extract_map
  13. result = Hash.new
  14. each_with_index do |item, index|
  15. e = yield item, index
  16. result[item] = e unless e.nil?
  17. end
  18. result
  19. end
  20.  
  21. def extract_one
  22. hide_from_stack = true
  23. each_with_index do |item, index|
  24. result = yield item, index
  25. return result if result
  26. end
  27. nil
  28. end
  29.  
  30. def expand(method)
  31. hide_from_stack = true
  32. result = ActiveArray.new
  33. each do |item|
  34. result.merge item.send(method)
  35. end
  36. result
  37. end
  38.  
  39. def max_value
  40. max = nil
  41. each do |item|
  42. value = yield item
  43. if not max or (value and value > max)
  44. max = value
  45. end
  46. end
  47. max
  48. end
  49.  
  50. end
  51.  
  52. Set.class_eval do
  53. include IterationsSugar
  54. end
  55.  
  56. Array.class_eval do
  57. include IterationsSugar
  58.  
  59.  
  60. alias some? any?
  61. alias index_of find_index
  62. alias filter select
  63. alias remove delete
  64.  
  65. def merge(other)
  66. if other.is_a? Array
  67. self.concat other
  68. else
  69. self << other
  70. end
  71. end
  72.  
  73. def merge_uniq(other)
  74. other.each do |element|
  75. self << element unless include? element
  76. end
  77. end
  78.  
  79. def intersects?(other)
  80. not (self & other).empty?
  81. end
  82.  
  83. def find!(&block)
  84. find(&block) || error("Not found")
  85. end
  86.  
  87. # fix compact! to act properly
  88. alias original_compact! compact!
  89. def compact!
  90. original_compact!
  91. self
  92. end
  93.  
  94. def add?(value)
  95. self << value if value
  96. end
  97.  
  98. def single!
  99. r = take_the_only
  100. error 'Нет элемента, а нужен' if r.nil?
  101. r
  102. end
  103.  
  104. def take_the_only
  105. if count > 1
  106. error "Много объектов, а нужно не больше одного: #{self}"
  107. end
  108. first
  109. end
  110.  
  111. def find_class(cls)
  112. hide_from_stack = true
  113. find { |item| item.is_a? cls }
  114. end
  115. alias some_is_a? find_class
  116. alias has_class? find_class
  117.  
  118. end
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement