一定量のカテゴリを持つ大規模なデータセットがあります。私はもともとすべてをハッシュの配列に格納してきました。うまく機能しますが、データのサイズとカテゴリの冗長性を考慮すると、効率的ではありません。
現在、さまざまなタイプ/カテゴリのハッシュを使用し、各カテゴリ内にハッシュの配列を格納しています。
現在、データを追加する現在の方法は:type
、型配列に追加する前に各ハッシュのキーを削除することです。すべてが機能しています。それにもかかわらず、私はこれを行うためのより合理化された「ルビーの方法」があると確信しています:
# Very large data set with redundant types.
gigantic_array = [
{ type: 'a', organization: 'acme inc', president: 'bugs bunny' },
{ type: 'a', organization: 'looney toons', president: 'donald' },
{ type: 'b', organization: 'facebook', president: 'mark' },
{ type: 'b', organization: 'myspace', president: 'whoknows' },
{ type: 'c', organization: 'walmart', president: 'wall' }
# multiply length by ~1000
]
# Still gigantic, but more efficient.
# Stores each type as symbol.
# Each type is an array of hashes.
more_efficient_hash = {
type: {
a: [
{ organization: 'acme inc', president: 'bugs bunny' },
{ organization: 'looney toons', president: 'donald' }
],
b: [
{ organization: 'facebook', president: 'mark' },
{ organization: 'myspace', president: 'whoknows' }
],
c: [
{ organization: 'walmart', president: 'wall' }
# etc....
]
}
}
hash_to_add = { type: 'c', organization: 'target', president: 'sharp' }
# Adds hash to array of types inside the gigantic more_efficient_hash.
# Is there a better way?
more_efficient_hash[:type][hash_to_add[:type].to_sym].push(hash_to_add.delete(:type))
いくつかの小さなデータクラスが役立つこと、および結果のキーが値を追加しないことについて、undur_gongorに同意し:type
ます。
からの最初の変換はgigantic_array
、で簡単に行うことができますgroup_by
。Hash#delete
はハッシュではなく削除されたキーの値を返すので、最後の行が希望どおりに機能しているとは思えないことに注意してください。
> more_efficient_hash = gigantic_array.group_by {|item| item.delete(:type).to_sym}
{
a: [
{:organization=>"acme inc", :president=>"bugs bunny"},
{:organization=>"looney toons", :president=>"donald"}
],
b: [
{:organization=>"facebook", :president=>"mark"},
{:organization=>"myspace", :president=>"whoknows"}
],
c: [
{:organization=>"walmart", :president=>"wall"}
]
}
その時点から、最後の行はかなりきれいです。delete
破壊的であるため、少し短くすることができます。
> more_efficient_hash[hash_to_add.delete(:type).to_sym] << hash_to_add
# ...
c: [
{:organization=>"walmart", :president=>"wall"},
{:organization=>"target", :president=>"sharp"}
]
この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。
侵害の場合は、連絡してください[email protected]
コメントを追加