“地图"是什么意思?方法在 Ruby 中做什么? [英] What does the "map" method do in Ruby?

查看:24
本文介绍了“地图"是什么意思?方法在 Ruby 中做什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是编程新手.谁能解释一下 .map 会做什么:

I'm new to programming. Can someone explain what .map would do in:

params = (0...param_count).map

推荐答案

map 方法接受一个可枚举对象和一个块,并为每个元素运行块,从块中输出每个返回值(除非你使用 map!,否则原始对象是不变的!):

The map method takes an enumerable object and a block, and runs the block for each element, outputting each returned value from the block (the original object is unchanged unless you use map!):

[1, 2, 3].map { |n| n * n } #=> [1, 4, 9]

ArrayRange 是可枚举类型.map 带有一个块返回一个数组.map! 改变原始数组.

Array and Range are enumerable types. map with a block returns an Array. map! mutates the original array.

这有什么用,map!each 有什么区别?这是一个例子:

Where is this helpful, and what is the difference between map! and each? Here is an example:

names = ['danil', 'edmund']

# here we map one array to another, convert each element by some rule
names.map! {|name| name.capitalize } # now names contains ['Danil', 'Edmund']

names.each { |name| puts name + ' is a programmer' } # here we just do something with each element

输出:

Danil is a programmer
Edmund is a programmer

这篇关于“地图"是什么意思?方法在 Ruby 中做什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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