MxLDevs
MxLDevs

Reputation: 19556

Appending n elements to an array

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

Answers (2)

Phrogz
Phrogz

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

David Grayson
David Grayson

Reputation: 87541

array = hash.flat_map { |k,v| [v]*k }

Upvotes: 17

Related Questions