我有以下简单的代码:
max_length = 0
chains.each { |x| if x.resolution < min_resolution min_resolution = x.resolution }
chains.delete_if { |x| x.resolution > min_resolution }
其中
chain
s具有属性resolution
,我想删除所有不具有最低chain
的resolution
s。这个解决方案有效,但我试图保持代码整洁,并试图避免局部变量。有没有办法在不创建变量max_length
的情况下解决上述问题? 最佳答案
#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>, ...]