“地图"有什么作用?方法在 Ruby 中做什么? [英] What does the "map" method do in Ruby?
本文介绍了“地图"有什么作用?方法在 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]
Array
和 Range
是可枚举类型.带有块的 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屋!
查看全文