将each_with_index与地图一起使用
我想取一个数组并将其作为一个订单列表。 目前我正在尝试这样做:
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"]
输出应该是["1. a", "2. b", "3. c"]
。
如何将正确的输出作为r
数组的新值?
a.to_enum.with_index(1).map {|element,i| "#{i}.#{element}"} or a.map.with_index(1){|element,index| "#{index}.#{element}"}
两种解决方案都可以。 with_index(1)生成第一个元素1的索引。在第一个解决方案中,数组转换为枚举,在后面的解决方案中,直接映射数组。
你需要先映射,然后puts
:
r = %w[abc] 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
这是因为each
(和each_with_index
)只返回原始数组。
> => r.each_with_index.map { |w, index| "#{index+1}. #{w}" } > => ["1. a", "2. b", "3. c"]