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
Add a comment |
1 Answer
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 2 Comments
user1934428
Instead of
"#{i}-#{name}", maybe it is clearer to write something like name.prepend.(i+'-'). This is of course a matter of taste. In addition, there is a functional difference: If name is not a String, but, for instance, nil or a number, this would be silently accepted in your code, while the solution with prepend would raise an exception. Which one is the desired behaviour here, I can't tell.user1934428
Sorry, should of course be
name.prepend.("#{i}-").