什么是“地图”方法做Ruby? [英] What does the "map" method do in Ruby?
本文介绍了什么是“地图”方法做Ruby?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
.map
将执行以下操作: params =( 0 ... param_count).map
解决方案
map
方法使用可枚举的对象和块,并为每个元素运行块,从块中输出每个返回的值(原始对象不变,除非使用地图!)
:
[1,2,3] .map {| n | n * n}#=> [1,4,9]
Array
和 Range
是枚举类型。带有块的 map
返回一个Array。 map!
突变原始数组。
这在哪里有帮助,以及 map!
和 each
?这里有一个例子:
names = ['danil','edmund']
#here我们将一个数组映射到另一个数组,通过一些规则
names.map来转换每个元素! {|名称| name.capitalize}#现在名字包含['Danil','Edmund']
names.each {| name |放置名称+'是一个程序员'}#这里我们只是为每个元素做一些事情
输出:
Danil是一个程序员
Edmund是一个程序员
I'm new to programming. Can someone explain what .map
would do in:
params = (0...param_count).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
and Range
are enumerable types. map
with a block returns an Array. map!
mutates the original array.
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
The output:
Danil is a programmer
Edmund is a programmer
这篇关于什么是“地图”方法做Ruby?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文