我正在用红宝石编写一个流程来计算最高统计数据。我有一个关于如何过滤对象数组的问题。
给定以下对象数组,它按经纪商,avg_price和avg_rating排序。
data = [
{name: "something1", brokerage: "some broker1", avg_price: 100, avg_rating: 1},
{name: "something2", brokerage: "some broker1", avg_price: 90, avg_rating: 2},
{name: "something3", brokerage: "some broker1", avg_price: 80, avg_rating: 3},
{name: "something4", brokerage: "some broker2", avg_price: 100, avg_rating: 1},
{name: "something5", brokerage: "some broker2", avg_price: 90, avg_rating: 2},
{name: "something6", brokerage: "some broker2", avg_price: 80, avg_rating: 3},
{name: "something7", brokerage: "some broker3", avg_price: 100, avg_rating: 1},
{name: "something8", brokerage: "some broker3", avg_price: 90, avg_rating: 2},
{name: "something9", brokerage: "some broker3", avg_price: 80, avg_rating: 3},
{name: "something10", brokerage: "some broker4", avg_price: 100, avg_rating: 1}]
是否有任何地图,收集,选择等功能,这将允许我将此数组减少到:
[{:name=>"something1", :brokerage=>"some broker1", :avg_price=>100, :avg_rating=>1},
{:name=>"something4", :brokerage=>"some broker2", :avg_price=>100, :avg_rating=>1},
{:name=>"something7", :brokerage=>"some broker3", :avg_price=>100, :avg_rating=>1},
{:name=>"something10", :brokerage=>"some broker4", :avg_price=>100, :avg_rating=>1}]
后者让我成为每个经纪公司的顶级经纪人。我知道这是可行的,使用每个块,只需写出新经纪人的第一个实例。我只是想知道ruby是否有内置功能。
答案 0 :(得分:0)
假设您已经计算了 avg_rating 中的最高评分,并希望返回 avg_rating 等于 1 的那些,您可以申请struct Foo {
private var storedStrings = Set<String>()
mutating func insertNewStoredString(_ newString: String) {
if storedStrings.insert(newString).0 {
print("Inserted '\(newString)' into storedStrings")
}
}
}
var foo = Foo()
foo.insertNewStoredString("hello") // Inserted 'hello' into storedStrings
foo.insertNewStoredString("hello")
foo.insertNewStoredString("world") // Inserted 'world' into storedStrings
方法如下:Enumerable#select
如果您不能依赖 avg_rating 并希望确定每个代理商的每个帐户的顶级 avg_price ,您可以转换数据集并执行一些分析...
data.select {|c| c[:avg_rating] == 1 }
其中任何一个都会产生所需的最终数组:
# Collect hash of all brokers and prepare an array of names
brokers = Hash[data.map{|c| c[:brokerage] }.uniq.zip.map{|c| c.push []}]
# Fill our brokers hash with each account they are responsible for
data.each_with_object(brokers) do |account,brokers|
brokers[account[:brokerage]].push account
end
# Determine the top account per broker using our brokers Hash
brokers.map {|key,arr| arr.max_by{|x| x[:avg_price] }}