Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using each_with_index with map

Tags:

ruby

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?

like image 738
Adam D. Bell Avatar asked Nov 18 '13 05:11

Adam D. Bell


3 Answers

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.

like image 166
sufinsha Avatar answered Oct 05 '22 20:10

sufinsha


> => r.each_with_index.map { |w, index| "#{index+1}. #{w}" }

> => ["1. a", "2. b", "3. c"]
like image 26
M.I. Avatar answered Oct 05 '22 21:10

M.I.


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.

like image 40
Andrew Marshall Avatar answered Oct 05 '22 22:10

Andrew Marshall