public
Created

Obtain the smalles n items from an Enumerable

  • Download Gist
Enum_n_min_1.rb
Ruby
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
module Enumerable
def n_min(n)
raise "Illegal argument: #{n.inspect}" unless n > 0
mins = []
each do |item|
mins.push item
mins.sort!
mins.pop if mins.size > n
end
mins
end
end
Enum_n_min_2.rb
Ruby
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
module Enumerable
def n_min(n)
raise "Illegal argument: #{n.inspect}" unless n > 0
 
mins = []
 
each do |item|
mins.size.times do |i|
if item < mins[i]
mins.insert i, item
break false
end
end and mins.push item
 
mins.pop if mins.size > n
end
 
mins
end
end
Enum_n_min_3.rb
Ruby
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
module Enumerable
def n_min(n)
raise "Illegal argument: #{n.inspect}" unless n > 0
 
mins = []
 
each do |item|
mins.size.times do |i|
if item < mins[i]
mins.insert i, item
mins.pop if mins.size > n
break false
end
end and mins.size < n and mins.push item
end
 
mins
end
end

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.