Guilherme Luiz
Guilherme Luiz

Reputation: 127

How to prepend elements in array ruby?

I'd like to prepend 'n-' in the elements of an array being n the number of the index of the element and after that reverse it the array is ["Abricot du Laudot", "Black Caviar", "Brigadier Gerard", "Coup de Folie"] and I need it to be like that ["4-Brigadier Gerard!", "3-Coup de Folie!", "2-Black Caviar!", "1-Abricot du Laudot!"] so far I've tried race_array.map! { |horse| horse.prepend() }.reverse! but could not find a way to put the number index into the prepend function or using each method

Upvotes: 0

Views: 510

Answers (1)

AmitA
AmitA

Reputation: 3245

In order to get the index injected into the map block, you need to call an enumerator method that sends the index to the block. Here are a few options:

race_array = ["Abricot du Laudot", "Black Caviar", "Brigadier Gerard", "Coup de Folie"]

# Use `each_with_index` before calling `map`
race_array.each_with_index.map{ |name, i| "#{i+1}-#{name}" }.reverse
# => ["4-Coup de Folie", "3-Brigadier Gerard", "2-Black Caviar", "1-Abricot du Laudot"]

# Use `with_index` after calling `map`
race_array.map.with_index{ |name, i| "#{i+1}-#{name}" }.reverse
# => ["4-Coup de Folie", "3-Brigadier Gerard", "2-Black Caviar", "1-Abricot du Laudot"]

# Similarly, you can call `with_index` with an offset:
race_array.map.with_index(1){ |name, i| "#{i}-#{name}" }.reverse
# => ["4-Coup de Folie", "3-Brigadier Gerard", "2-Black Caviar", "1-Abricot du Laudot"]

See this question for more information.

And for a more "exotic" solution (though less readable), you could combine an index with each element of the array, and then join the result:

(1..race_array.length).zip(race_array).map{|x| x.join('-')}.reverse

Upvotes: 4

Related Questions