如何定Array#新的工作块形式" Array.new(10){| E | E = E * 2}"? [英] How does the block form of Array#new work given "Array.new(10) { |e| e = e * 2 }"?

查看:285
本文介绍了如何定Array#新的工作块形式" Array.new(10){| E | E = E * 2}"?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我无法理解花括号内的部分。

I am having trouble understanding the part inside the curly braces.

Array.new(10) { |e| e = e * 2 }
# => [0, 2, 4, 6, 8, 10, 12, 14, 16, 18]   

我得到与十个值的新数组被创建,但什么是下半年做什么?

I get that a new array with ten values is created, but what is the second half doing?

推荐答案

让我们在这个具体为:

nums = Array.new(10)

这将创建10个元素的新数组。对于每个数组元素。它经过指定的控制块:

This creates a new array with 10 elements. For each array element it passes control to the block specified by:

{ |e| e = e * 2 }

| E | 重新presents元素的索引。该指数是阵列中的位置。这从0开始,因为数组有10个元素在9结束。第二部分乘以2的索引和返回值。这是因为 E * 2 ,是该块中的最后一条语句,则返回。 返回,然后应用到该元素的值的值因此,我们最终用下面的数组:

The |e| represents the element's index. The index is the position in the array. This starts at 0 and ends at 9 since the array has 10 elements. The second part multiplies the index by 2 and returns the value. This is because the e * 2, being the last statement in the block, is returned. The value returned is then applied to that element's value. So we end up with the following array:

[0, 2, 4, 6, 8, 10, 12, 14, 16, 18]

修改

正如PJS,避免在路上,问题写在同一code更简单的方式提到的是:

As mentioned by pjs and to avoid problems down the road, a simpler way to write the same code would be:

Array.new(10) { |e| e * 2 }

这篇关于如何定Array#新的工作块形式" Array.new(10){| E | E = E * 2}"?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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