Ruby 数组的where方法

Ruby 数组的where方法,ruby,methods,hash,Ruby,Methods,Hash,我很想模仿where的class方法,但是在一个实例上,这个实例是一个散列数组。例如:这是一个类方法类。其中:name=>Joe,所以我希望能够做到这一点: @joe = {:name => "Joe", :title => "Mr.", :job => "Accountant"} @kelly = {:name => "Kelly", :title => "Ms.", :job => "Auditor"} @people = [@joe, @kelly]

我很想模仿where的class方法,但是在一个实例上,这个实例是一个散列数组。例如:这是一个类方法类。其中:name=>Joe,所以我希望能够做到这一点:

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

@people.where(:name => 'Joe')
它应该返回@joe对象

我该怎么写

@people.find{|p| p[:name] =='Joe'}

用一种方法:

def find_user params
  @people.find(params).first
end

find_user name:'Joe'
=> {:name=>"Joe", :title=>"Mr.", :job=>"Accountant"}
您可以使用检索匹配的第一个元素:

@people.find     { |p| p[:name] == 'Joe' }
或检索匹配的所有元素:

@people.find_all { |p| p[:name] == 'Joe' }

它与Rails的where有点不同,更像是find_by: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.

如果您谈论的是实际的哈希数组,而不是活动记录:

@some_array.select {|item| item["search_key"] = 'search val' }

我希望这个方法是通用的,因为用户可以通过名字、头衔或工作进行搜索,并且这个方法可以通过它进行解析。我得到了nil:nilclassue@joe={:name=>joe,:title=>Mr,:job=>accountary}@kelly={:name=>kelly,:title=>Ms,:job=>Auditor}@people=[@joe,@kelly]。此错误表示未定义@people。你把这个方法放在一个类中了吗?是的,我把它放在数组类中了,做得很好,特别是添加了类和功能!现在你只需要合并或不合并。也许选择{e|e.is|u a?Hash&&Hash.all?{k,v | e.key?k&&e[k]==v},其中e.key?k允许哈希值为零。是否更新?or和not的功能在哪里?我不知道Rails,但我假设您提到的类方法来自ActiveRecord,因为没有Ruby方法Array::where。如果是这样,您应该进行编辑,使其读起来类似于,…以模拟类方法Array::where,。。。由ActiveRecord提供,但不添加Rails或ActiveRecord标记,imo。
@people.select { |h| h[:name] == 'Joe' } # where-like
@people.find   { |h| h[:name] == 'Joe' } # find_by-like
▶ 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')
#⇒ []
@some_array.select {|item| item["search_key"] = 'search val' }