0

重複の可能性:
ブロックなしの最大/最小のより簡潔なバージョン

特定の属性(この例では高さ)を持つオブジェクトがN個ある場合、最大または最小を見つける良い方法は何ですか?

 class Person
   attr_accessor: height
 end

 a = Person.new
 a.height = 10
 b = Person.new
 b.height = 11
 c = Person.new
 c.height = 12

 #what's a nice way to get the tallest person
4

1 に答える 1

5

ここで答えを拡張するには:

class Person
  attr_accessor :height

  def initialize(height)
    self.height = height
  end
end

people = [ Person.new(10), Person.new(20), Person.new(30) ]

tallest_person = people.max_by &:height
于 2012-05-17T08:51:17.330 に答える