我有紅寶石二維數組,並嘗試如下的數據合併:紅寶石合併數組有條件
a = [["a","1"],["b","2"],["c","2"],["d","3"],["e","4"],["f","4"],["g","4"]]
我希望把它變成
[["a"],["b c"],["d"],["e f g"]] //merge each letter together if they have the same "key"
誰能幫我找出什麼是最有效的方法呢?謝謝。要做到這一點
我有紅寶石二維數組,並嘗試如下的數據合併:紅寶石合併數組有條件
a = [["a","1"],["b","2"],["c","2"],["d","3"],["e","4"],["f","4"],["g","4"]]
我希望把它變成
[["a"],["b c"],["d"],["e f g"]] //merge each letter together if they have the same "key"
誰能幫我找出什麼是最有效的方法呢?謝謝。要做到這一點
一種方式是通過在每個陣列中的第二個值使用group_by
到組元素,然後使用map
收集並格式化相關的值:
a.group_by(&:last).map { |k,v| [v.map(&:first).join(' ')] }
#=> => [["a"], ["b c"], ["d"], ["e f g"]]
查看在Ruby documentationgroup_by
和map
更多信息。
使用哈希可以是解決它的一種方法。
initial_array = [["a","1"],["b","2"],["c","2"],["d","3"],["e","4"],["f","4"],["g","4"]]
constructed_hash = {}
initial_array.each do |item|
constructed_hash[item[1]] = constructed_hash[item[1]].to_a << item[0]
end
final_array = constructed_hash.values
像'_array'和'_hash'這樣的東西雜亂無章地表達了這個解決方案,但這是一個解決方案。不要忘記你可以分解數組中的元素:'每個都做| a,b |'避免'item [0]'和'item [1]'。 – tadman
這應該對你很好,儘管它確實建立了一箇中介Hash
它只需要一次迭代。
a.each_with_object(Hash.new {|h,k| h[k] =''}) do |(v, k),obj|
(obj[k] << " #{v}").strip!
end.values
#=> ["a", "b c", "d", "e f g"]
或使用Array
(假定的「鑰匙」是數字和位置就像他們在這個問題,否則恢復選項1)
a.each_with_object([]) do |(v,k), obj|
((obj[k.to_i - 1] ||= "") << " #{v}").strip!
end
#=> ["a", "b c", "d", "e f g"]
請試一下,詢問一下可枚舉#GROUP_BY前給它一個鏡頭 – engineersmnky
這是一個非常奇特的目標格式。 – tadman
@tadman我想知道OP是否意味着'[[「a」],[「b」,「c」],[「d」],[「e」,「f」,「g」]]。 –