Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

I have the following array structure:

[   ["one_id",[["1a", 10], ["1b", 54], ["1c", 43]]], 
    ["two_id",[["2a", 32], ["2b", 76], ["2c", 34]]], 
    ["thr_id",[["3a", 85], ["3b", 13], ["3c", 42]]], 
    ["fou_id",[["4a", 15], ["4b", 21], ["4c", 65]]], 
]

And I would like to drop the "value" of the nested arrays to get to an output like:

[   ["one_id",  ["1a","1b","1c"]], 
    ["two_id",  ["2a","2b","2c"]], 
    ["thr_id",  ["3a","3b","3c"]], 
    ["fou_id",  ["4a","4b","4c"]], 
]

Any suggestion?

share|improve this question

4 Answers 4

up vote 2 down vote accepted

This is a non-destructive one:

array.map{|k, v| [k, v.map(&:first)]}
#=> [
  ["one_id", ["1a", "1b", "1c"]],
  ["two_id", ["2a", "2b", "2c"]],
  ["thr_id", ["3a", "3b", "3c"]],
  ["fou_id", ["4a", "4b", "4c"]]
]
share|improve this answer

If by "drop the 'value'" you meant "replace innermost array to its first element:

Warning: this code contains magic number and is not even general.

require "pp"

a = [   ["one_id",[["1a", 10], ["1b", 54], ["1c", 43]]],
        ["two_id",[["2a", 32], ["2b", 76], ["2c", 34]]],
        ["thr_id",[["3a", 85], ["3b", 13], ["3c", 42]]],
        ["fou_id",[["4a", 15], ["4b", 21], ["4c", 65]]],
]

a.each do |lv1|
  lv1[1].map! &:first
end

pp a

# => 
# [["one_id", ["1a", "1b", "1c"]],
# ["two_id", ["2a", "2b", "2c"]],
# ["thr_id", ["3a", "3b", "3c"]],
# ["fou_id", ["4a", "4b", "4c"]]]
share|improve this answer

There is the code

arr = [   ["one_id",[["1a", 10], ["1b", 54], ["1c", 43]]], 
    ["two_id",[["2a", 32], ["2b", 76], ["2c", 34]]], 
    ["thr_id",[["3a", 85], ["3b", 13], ["3c", 42]]], 
    ["fou_id",[["4a", 15], ["4b", 21], ["4c", 65]]], 
]

arr2 = arr.map do |element|
    r = [element[0]]
    r << element[1].map(&:first)
    r
end
share|improve this answer
    require "pp"

    array = [   ["one_id",[["1a", 10], ["1b", 54], ["1c", 43]]],
            ["two_id",[["2a", 32], ["2b", 76], ["2c", 34]]],
            ["thr_id",[["3a", 85], ["3b", 13], ["3c", 42]]],
            ["fou_id",[["4a", 15], ["4b", 21], ["4c", 65]]],
    ]

    array.collect{|k, v| [k, v.collect(&:first)]}

# [["one_id", ["1a", "1b", "1c"]], 
#  ["two_id", ["2a", "2b", "2c"]], 
#  ["thr_id", ["3a", "3b", "3c"]], 
#  ["fou_id", ["4a", "4b", "4c"]]]
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.