Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- module IterationsSugar
- def extract
- result = ActiveArray.new
- each_with_index do |item, index|
- e = yield item, index
- result << e unless e.nil?
- end
- result
- end
- def extract_map
- result = Hash.new
- each_with_index do |item, index|
- e = yield item, index
- result[item] = e unless e.nil?
- end
- result
- end
- def extract_one
- hide_from_stack = true
- each_with_index do |item, index|
- result = yield item, index
- return result if result
- end
- nil
- end
- def expand(method)
- hide_from_stack = true
- result = ActiveArray.new
- each do |item|
- result.merge item.send(method)
- end
- result
- end
- def max_value
- max = nil
- each do |item|
- value = yield item
- if not max or (value and value > max)
- max = value
- end
- end
- max
- end
- end
- Set.class_eval do
- include IterationsSugar
- end
- Array.class_eval do
- include IterationsSugar
- alias some? any?
- alias index_of find_index
- alias filter select
- alias remove delete
- def merge(other)
- if other.is_a? Array
- self.concat other
- else
- self << other
- end
- end
- def merge_uniq(other)
- other.each do |element|
- self << element unless include? element
- end
- end
- def intersects?(other)
- not (self & other).empty?
- end
- def find!(&block)
- find(&block) || error("Not found")
- end
- # fix compact! to act properly
- alias original_compact! compact!
- def compact!
- original_compact!
- self
- end
- def add?(value)
- self << value if value
- end
- def single!
- r = take_the_only
- error 'Нет элемента, а нужен' if r.nil?
- r
- end
- def take_the_only
- if count > 1
- error "Много объектов, а нужно не больше одного: #{self}"
- end
- first
- end
- def find_class(cls)
- hide_from_stack = true
- find { |item| item.is_a? cls }
- end
- alias some_is_a? find_class
- alias has_class? find_class
- end
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement