Reputation: 1358
I have the following simple code:
max_length = 0
chains.each { |x| if x.resolution < min_resolution min_resolution = x.resolution }
chains.delete_if { |x| x.resolution > min_resolution }
where chain
s have the property resolution
, and I want to delete all chain
s that don't have the lowest resolution
. This solution works, but I'm trying to keep my code tidy and am trying to avoid local variables. Is there a way to solve the problem above without creating the variable max_length
?
Upvotes: 1
Views: 107
Reputation: 80065
#sample data:
Chain = Struct.new(:resolution)
chains = 1000.times.map{Chain.new(rand(100))}
# do work:
p chains.group_by(&:resolution).min.last
#=>[#<struct Chain resolution=0>, #<struct Chain resolution=0>, ...]
Upvotes: 5
Reputation: 168091
I am not sure if I get the question correctly. Under the interpretation that you do not have or need duplicates, I think this is enough:
[chains.min_by(&:resolution)]
Upvotes: 1
Reputation: 230316
From the top of my head I don't see a way without precalculating minimal value before deletion. But you can prettify the code. What about this?
min_res = chains.map(&:resolution).min
chains.delete_if {|c| c.resolution > min_res }
Upvotes: 5