📅  最后修改于: 2023-12-03 15:34:45.953000             🧑  作者: Mango
在Ruby中,可以通过数组的select方法和对象的属性来查找数组中与属性匹配的对象。
class Person
attr_accessor :name, :age
def initialize(name, age)
@name = name
@age = age
end
end
people = [
Person.new("Alice", 25),
Person.new("Bob", 30),
Person.new("Charlie", 35)
]
# 按年龄查找
result = people.select { |person| person.age == 30 }
puts result.first.name #=> "Bob"
# 按姓名查找
result = people.select { |person| person.name == "Charlie" }
puts result.first.age #=> 35
在上面的例子中,我们定义了一个Person类,包含name和age两个属性。然后创建了一个people数组,其中包含三个Person对象。
使用select方法,在数组中按属性查找对象,如果匹配成功,将返回一个数组包含符合条件的对象。在上面的例子中,我们可以通过按年龄和姓名查找来获取数组中的对象。
find
方法。通过使用Ruby的select方法,可以方便地在数组中按对象属性查找符合条件的对象。在实际开发中,这种方式经常用于数据过滤和处理。