在没有`map`或`collect`方法的情况下,如何在红宝石中对数字数组求平方? [英] How to square an array of numbers in ruby without `map` or `collect` methods?

查看:122
本文介绍了在没有`map`或`collect`方法的情况下,如何在红宝石中对数字数组求平方?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我目前拥有的代码

def square_array(array)
    array.each do |i|
      i ** 2
    end
end

我知道这是不正确的,有人可以向我解释此过程吗?

I know it's not correct, could someone explain this process to me please?

推荐答案

each<<与空数组一起使用

Using each and << with an empty array

def square_array(array)
  arr = []
  array.each { |i| arr << i ** 2 }
  arr
end

my_arr = [1, 2]
p square_array(my_arr) #=> [1, 4]

在这里,我们创建了一个新的空数组arr.然后,我们遍历另一个作为参数传递的数组array,在将每个元素(使用<<)推入新数组arr之前,对每个元素进行平方运算.

Here we've created a new empty array arr. We then iterate through the other array array which is passed as an argument, squaring each element before pushing it (using <<) into our new array arr.

最后,我们通过简单地将arr写入方法块的最后一行来返回新创建的数组arr.我们本可以写return arr,但是在Ruby中,可以省略return关键字.

Finally we return the newly created array arr by simply writing arr as the final line in the method block. We could have written return arr but in Ruby the return keyword can be omitted.

使用each_with_object

Using each_with_object

上述技术的细微发展

def square_array(array)
  array.each_with_object([]) { |i,arr| arr << i ** 2 }
end

my_arr = [1, 2]
p square_array(my_arr) #=> [1, 4]


each与枚举器一起使用


Using each with an Enumerator

def square_array(array)
  Enumerator.new do |y|
    array.each { |e| y << e ** 2 }    
  end
  .take(array.length)
end

my_arr = [1, 2, 3, 4]
p square_array(my_arr) #=> [1, 4, 9, 16]

在这里,我们创建一个新的枚举器.然后,我们为枚举器编写指令,告诉枚举器(在被调用时)根据each块产生值y.

Here we create a new enumerator. We then write instructions for the enumerator telling it (when called upon) to yield values y according to the each block.

然后,我们使用take调用给定数组的所有产生的值,这将返回具有所述值的数组.

We then call all the yielded values for the given array by using take which returns an array with said values.

这篇关于在没有`map`或`collect`方法的情况下,如何在红宝石中对数字数组求平方?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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