Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Appending n elements to an array

Tags:

arrays

ruby

I have an array and a hash

L = []
H = {3=>"a", 2=>"b", 1=>"c"}

And so I will iterate over the keys to get the number of times n the element occurs and append that element to an array n times

Result

L = ['a', 'a', 'a', 'b', 'b', 'c']

What's a nice way to write this with inject (or other methods that I often see in ruby code)?

like image 548
MxLDevs Avatar asked Dec 01 '22 23:12

MxLDevs


1 Answers

array = hash.flat_map { |k,v| [v]*k }
like image 65
David Grayson Avatar answered Dec 04 '22 08:12

David Grayson