gpt4 book ai didi

ruby - 数组的where方法

转载 作者:数据小太阳 更新时间:2023-10-29 07:46:10 25 4
gpt4 key购买 nike

我几乎是在尝试模仿 where 的类方法,但不是在一个实例上,这个实例是一个散列数组。例如:这作为一个类方法 Class.where(:name => "Joe") 存在,所以我希望能够这样做:

@joe = {:name => "Joe", :title => "Mr.", :job => "Accountant"}
@kelly = {:name => "Kelly", :title => "Ms.", :job => "Auditor"}
@people = [@joe, @kelly]

并调用它:

@people.where(:name => 'Joe')

它应该返回 @joe 对象。

这个应该怎么写?

最佳答案

根据我对任务的理解,您需要定义 Array#where。给你:

▶ class Array
▷ def where hash
▷ return nil unless hash.is_a? Hash # one might throw ArgumentError here
▷ self.select do |e|
▷ e.is_a?(Hash) && hash.all? { |k, v| e.key?[k] && e[k] == v }
▷ end
▷ end
▷ end
#⇒ :where
▶ @people.where(:name => 'Joe')
#⇒ [
# [0] {
# :job => "Accountant",
# :name => "Joe",
# :title => "Mr."
# }
# ]
▶ @people.where(:name => 'Joe', :job => 'Accountant')
#⇒ [
# [0] {
# :job => "Accountant",
# :name => "Joe",
# :title => "Mr."
# }
# ]
▶ @people.where(:name => 'Joe', :job => 'NotAccountant')
#⇒ []

希望对您有所帮助。

UPD 稍微更新了区分nil 值和缺失键的功能。感谢@CarySwoveland。

关于ruby - 数组的where方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30331392/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com