Reputation: 19556
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)?
Upvotes: 4
Views: 770
Reputation: 303559
@David's answer is spot-on for your needs. In general, however, you can add an object o to an existing array n times via one of:
# Modify the array in-place, or…
my_array.concat( [o]*n )
# …alternatively create a new modified array
new_array = my_array + [o]*n
Upvotes: 2