ruby - Consolidate nested arrays and erase the subarrays that have been consolidated? -
i'm trying take bunch of number-word pairs , group words according common numbers. can match numbers, merge subarrays share number, , erase first of subarrays. when try delete second, error:
"in block in <main>': undefined method
[]' nil:nilclass (nomethoderror)"
the guilty line -- ary.delete_at(i+1) -- has been commented out. secondary problem: mrbtree not taking nested arrays input...
ary = [[2.28, "cat"], [2.28, "bat"], [2.327, "bear"], [2.68, "ant"], [2.68, "anu"]] = 0 in 0 ... ary.size - 1 if ary[i][0] == ary[i+1][0] b = (ary[i]+ary[i+1]).uniq ary.delete_at(i) # ary.delete_at(i+1) c = [b.first], b.pop(b.length - 1) h = hash[*c] ary.push(*h) # mrbtree = multirbtree[c] end end puts ary.inspect
output:
# => [ # => [2.28, "bat"], # => [2.327, "bear"], # => [2.68, "anu"], # => [ # => [2.28], ["cat", "bat"] # => ], # => [ # => [2.68], ["ant", "anu"] # => ] # => ]
any appreciated!
your attempt failing because modifying array (which has impact on a.size
) in loop. loop end condition not adjusted automagically. accessing things have deleted before.
if array not big, do:
p hash[ary.group_by(&:first).map { | k, v | [k, v.map(&:last)] }] # => {2.28=>["cat", "bat"], 2.327=>["bear"], 2.68=>["ant", "anu"]}
it works way:
ary.group_by(&:first) # group 2-elem arrays number, creating hash # {2.28=>[[2.28, "cat"], [2.28, "bat"]], ...} .map { | k, v | ... } # change array of key-value pairs [k, v.map(&:last)] # pairs value-array contains strings hash[ ... ] # make whole thing hash again
creating intermediate array , transferring hash overhead. if turns out issue, might better:
h = hash.new { | a, k | a[k] = [] } # hash [] default value p ary.inject(h) { | a, (k, v) | a[k] << v; }
Comments
Post a Comment