0

I'm trying to combine an array of hashes like this:

[{:locale=>:"en-US", :key=>:key1}, 
 {:locale=>:"en-US", :key=>:key2}, 
 {:locale=>:da,      :key=>:key1}]

Into one array like this:

['locale', 'en-US', 'key', 'key1', 
 'locale', 'en-US', 'key', 'key2', 
 'locale', 'da',    'key', 'key1']

How can I do this?

1
  • 1
    please make an attempt before asking for help Commented Oct 4, 2021 at 12:57

2 Answers 2

4

Input

a=[{:locale=>:"en-US", :key=>:key1}, {:locale=>:"en-US", :key=>:key2}, {:locale=>:da, :key=>:key1}]

Code

result=a.map do |h|
  h.map do|k,v|
    [k,v]
  end
end.flatten
p result

Or

p a.flat_map(&:to_a).flatten

Output

[:locale, :"en-US", :key, :key1, :locale, :"en-US", :key, :key2, :locale, :da, :key, :key1]
Sign up to request clarification or add additional context in comments.

3 Comments

Another option a.flat_map(&:flatten)
@rajagopalan Just map (no flat_map) is fine too.
Note that the OP wishes to construct an array of strings.
0

Or, even quicker and easier:

array = [{:locale=>:"en-US", :key=>:key1}, {:locale=>:"en-US", :key=>:key2}, {:locale=>:da, :key=>:key1}]
array.map { |hash| [hash.keys, hash.values] }.flatten

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.