0

I have 2d array like this:

ary = [
  ["Source", "attribute1", "attribute2"],
  ["db", "usage", "value"],
  ["import", "usage", "value"],
  ["webservice", "usage", "value"]
]

I want to pull out the following in hash:

{1 => "db", 2 => "import", 3 => "webservice"} // keys are indexes or outer 2d array

I know how to get this by looping trough 2d array. But since I'm learning ruby I thought I could do it with something like this

ary.each_with_index.map {|element, index| {index => element[0]}}.reduce(:merge)

This gives me :

{0=> "Source", 1 => "db", 2 => "import", 3 => "webservice"}

How do I get rid of 0 element from my output map?

2 Answers 2

1

I'd write:

Hash[ary.drop(1).map.with_index(1) { |xs, idx| [idx, xs.first] }]
#=> {1=>"db", 2=>"import", 3=>"webservice"}
Sign up to request clarification or add additional context in comments.

Comments

0

ary.drop(1) drops the first element, returns the rest.

You could build the hash directly without the merge reduction using each_with_object

ary.drop(1)
  .each_with_object({})
  .with_index(1) { |((source,_,_),memo),i| memo[i] = source }

Or map to tuples and send to the Hash[] constructor.

Hash[ ary.drop(1).map.with_index(1) { |(s,_,_),i| [i, s] } ]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.