Ruby 相当于 ActiveRecord 'where'
Ruby equivalent of ActiveRecord 'where'
我有一个数组,我想通过 :city 进行过滤。使用 ActiveRecord 查询将是这样的:
MyBase.where(city: "NY")
如何在没有 ActiveRecord 方法的情况下仅使用纯 Ruby 过滤数组?
你应该使用 Array#select 方法。
array_of_objects.select { |o| o.city == "NY" }
示例:
Person = Struct.new(:name, :city)
array_of_persons = [ Person.new('A', 'foo'), Person.new('B', 'boo') ]
array_of_persons.select { |person| person.city == 'foo' }
# => [#<struct Person name="A", city="foo">]
我有一个数组,我想通过 :city 进行过滤。使用 ActiveRecord 查询将是这样的:
MyBase.where(city: "NY")
如何在没有 ActiveRecord 方法的情况下仅使用纯 Ruby 过滤数组?
你应该使用 Array#select 方法。
array_of_objects.select { |o| o.city == "NY" }
示例:
Person = Struct.new(:name, :city)
array_of_persons = [ Person.new('A', 'foo'), Person.new('B', 'boo') ]
array_of_persons.select { |person| person.city == 'foo' }
# => [#<struct Person name="A", city="foo">]