calben
calben

Reputation: 1358

Can I avoid creating a local variable when finding a maximum or minimum property in an Array?

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 chains have the property resolution, and I want to delete all chains 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

Answers (3)

steenslag
steenslag

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

sawa
sawa

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

Sergio Tulentsev
Sergio Tulentsev

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

Related Questions