I want to take a array and make it an order list. Currently I'm trying to do it in this way:
r = ["a", "b","c"]
r.each_with_index { |w, index| puts "#{index+1}. #{w}" }.map.to_a
# 1. a
# 2. b
# 3. c
#=> ["a", "b", "c"]
the output should be ["1. a", "2. b", "3. c"]
.
How do I get the proper output to be the new value for the r
array?
a.to_enum.with_index(1).map { |element, index| "#{index}. #{element}" }
or
a.map.with_index(1) { |element, index| "#{index}. #{element}" }
with_index(1)
makes the index of the first element 1
.
In the first solution the array is converted to an enum, and in the second solution the array is directly mapped.
> => r.each_with_index.map { |w, index| "#{index+1}. #{w}" }
> => ["1. a", "2. b", "3. c"]
You need to map first, then puts
:
r = %w[a b c]
r.map.with_index do |w, index|
"#{index + 1}. #{w}"
end.each do |str|
puts str
end
#=> ["1. a", "2. b", "3. c"]
# prints:
# 1. a
# 2. b
# 3. c
This is because each
(and each_with_index
) simply returns the original array.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With