我几乎试图模仿类的方法where,但在实例上,这个实例是一个哈希数组.例如:这作为一个类方法存在Class.where(:name => "Joe"),所以我希望能够这样做:
@joe = {:name => "Joe", :title => "Mr.", :job => "Accountant"}
@kelly = {:name => "Kelly", :title => "Ms.", :job => "Auditor"}
@people = [@joe, @kelly]
Run Code Online (Sandbox Code Playgroud)
并称之为:
@people.where(:name => 'Joe')
Run Code Online (Sandbox Code Playgroud)
哪个应该返回@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')
#? []
Run Code Online (Sandbox Code Playgroud)
希望能帮助到你.
UPD略微更新功能以区nil分值和缺少键.积分给@CarySwoveland.
| 归档时间: |
|
| 查看次数: |
337 次 |
| 最近记录: |