将 each_with_index 与地图一起使用 [英] Using each_with_index with map

查看:47
本文介绍了将 each_with_index 与地图一起使用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想获取一个数组并将其设为订单列表.目前我正在尝试这样做:

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"]

输出应该是["1.a", "2.b", "3.c"].

如何使正确的输出成为 r 数组的新值?

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}" }

a.map.with_index(1) { |element, index| "#{index}. #{element}" }

with_index(1) 使第一个元素的索引 1.

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.

这篇关于将 each_with_index 与地图一起使用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆