如何理解Ruby的.each和.map [英] How to understand Ruby's .each and .map

查看:48
本文介绍了如何理解Ruby的.each和.map的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我无法理解 map 每个之间的区别,以及何时何地使用它们.

我阅读了"地图做什么?"和" Ruby迭代器",但需要澄清一下.

如果我有

  z = [1,2,3] .map {| x |x + 1} 

map 接受数组 z 中的每个元素,并向每个元素添加一个,但是除非我添加!.

另一方面:

  y = [1,2,3].每个{| x |x + 1} 

返回 [1,2,3] .由于以下原因,这使我感到困惑:

  names = ['danil','edmund']名称.每个{|名称|放置名称+'是程序员'} 

返回:

  Danil是一名程序员Edmund是一位程序员 

在我的第二个示例中到底发生了什么,不允许每个数组元素增加 1 ,而在上一个示例中,字符串附加到了数组的所有内容上?/p>

所有功劳归功于Speransky Danil,我从这些例子中脱颖而出.

解决方案

map 方法采用给定一些代码块的 enum ,并通过一些逻辑对其进行迭代.在您的情况下,逻辑为 x + 1 .如您所说,除非您使用.

每个只是返回被调用的数组.

让我们举个例子:

 名称= ["bob"] 

如果我们这样做:

  names.each {| names |名称+"somestring"} 

输出仍然是 ["bob"] .您的第二个示例与众不同的原因是由于 puts .

尝试练习:

  y = [1,2,3].每个{| x |放x + 1} 

您将获得:

  234[1,2,3] 

I am having trouble understanding the differences between map and each, and where and when to use them.

I read "What does map do?" and "Ruby Iterators" but wanted some clarification.

If I have:

 z = [1,2,3].map {|x| x + 1}

map takes each element in the array z and adds one to each element, however it does not mutate the original array unless I add !.

On the other hand:

y = [1,2,3].each {|x| x + 1}

returns [1,2,3]. This is confusing to me since:

names = ['danil', 'edmund']
names.each { |name| puts name + ' is a programmer' }

returns:

Danil is a programmer
Edmund is a programmer

What is exactly going on in my second example that isn't allowing each array element to be increased by 1, while in the last example a string is being attached to everything in the array?

All credits go to Speransky Danil, whom I took these examples off of.

解决方案

The map method takes an enum given some block, and iterates through it doing some logic. In your case the logic is x+1. As you say it will not mutate anything unless you use !.

each is simply returning the array that is being called.

Let's take an example of:

names = ["bob"]

If we do:

names.each{|names| names + "somestring"}

the output is still ["bob"]. The reason your second example is different is due to the puts.

As an exercise try doing:

y = [1,2,3].each {|x| puts x + 1}

You will get:

2
3
4
 [1,2,3]

这篇关于如何理解Ruby的.each和.map的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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