Leo Leo - 1 month ago 6
Ruby Question

Create a Hash from two arrays of different sizes and iterate until none of the keys are empty

Having two arrays of different sizes, I'd like to get the

longer
array as keys and the
shorter
one as values. However, I don't want any keys to remain empty, so that is why I need to keep iterating on the
shorter
array until all keys have a value.

EDIT: I want to keep array longer intact, but without empty values, that means keep iterating on shorter until all keys have a value.

longer = [1, 2, 3, 4, 5, 6, 7]
shorter = ['a', 'b', 'c']

Hash[longer.zip(shorter)]
#=> {1=>"a", 2=>"b", 3=>"c", 4=>nil, 5=>nil, 6=>nil, 7=>nil}


Expected Result

#=> {1=>"a", 2=>"b", 3=>"c", 4=>"a", 5=>"b", 6=>"c", 7=>"a"}

Answer

Here's an elegant one. You can "loop" the short array

longer  = [1, 2, 3, 4, 5, 6, 7]
shorter = ['a', 'b', 'c']

longer.zip(shorter.cycle).to_h # => {1=>"a", 2=>"b", 3=>"c", 4=>"a", 5=>"b", 6=>"c", 7=>"a"}
Comments