lib/multi_range.rb in multi_range-0.0.1 vs lib/multi_range.rb in multi_range-0.0.2
- old
+ new
@@ -13,14 +13,16 @@
"You can use backports gem and add the following lines to your program:\n" \
"require 'backports/2.1.0/enumerable/to_h'"
end
class MultiRange
+ INDEX_WITH_DEFAULT = Object.new
+
attr_reader :ranges
def initialize(ranges) # range 要由小到大排序,且各 range 不能重疊
- @ranges = ranges
+ @ranges = ranges.map{|s| s.is_a?(Integer) ? s..s : s }
end
def -(other)
new_ranges = @ranges.clone
@@ -58,7 +60,30 @@
@ranges.inject(0){|sum, v| sum + v.size }
end
def any?
@ranges.any?
+ end
+
+ def index_with(default = INDEX_WITH_DEFAULT)
+ if block_given?
+ fail ArgumentError.new('wrong number of arguments (given 1, expected 0)') if default != INDEX_WITH_DEFAULT
+ return map{|s| [s, yield(s)] }.to_h
+ end
+
+ return to_enum(:index_with){ size } if default == INDEX_WITH_DEFAULT
+ return map{|s| [s, default] }.to_h
+ end
+
+ def each
+ return to_enum(:each){ size } if !block_given?
+
+ ranges.each do |range|
+ range.each{|s| yield(s) }
+ end
+ end
+
+ def map
+ return to_enum(:map){ size } if !block_given?
+ return each.map{|s| yield(s) }
end
end