M
Myrddin Emrys
I want to return part of a sorted array efficiently. The built in
iterators will search the entire array, but since I know it's sorted, I
only need to collect the items up until they stop being in range.
However, its pretty wasteful to keep iterating after they start to fall
out of range...
How do I break a .each (or .collect, .reject, etc) early?
For example:
#########################################################
class Item
attr_reader :level
def initialize
@level = rand(100)
end
end
list = Array.new(10) {Item.new}
list.sort {|a, b| a.level <=> b.level}
under50 = list.find {|item| item.level < 50} # wasteful!
#########################################################
Is there a simple way to do this? A rather complex solution would be to
create a routine to find the index where the transition from valid to
invalid occurred, and slice the array to that index... but just being
able to iterate over half of the items (rather than all) would be
efficient enough for me at this point.
iterators will search the entire array, but since I know it's sorted, I
only need to collect the items up until they stop being in range.
However, its pretty wasteful to keep iterating after they start to fall
out of range...
How do I break a .each (or .collect, .reject, etc) early?
For example:
#########################################################
class Item
attr_reader :level
def initialize
@level = rand(100)
end
end
list = Array.new(10) {Item.new}
list.sort {|a, b| a.level <=> b.level}
under50 = list.find {|item| item.level < 50} # wasteful!
#########################################################
Is there a simple way to do this? A rather complex solution would be to
create a routine to find the index where the transition from valid to
invalid occurred, and slice the array to that index... but just being
able to iterate over half of the items (rather than all) would be
efficient enough for me at this point.