【问题标题】:How can I operate on each element of an array and also collect or store those elements?如何对数组的每个元素进行操作并收集或存储这些元素?
【发布时间】:2016-09-27 14:02:51
【问题描述】:

我正在尝试构建一个方法,对数组的每个元素进行平方并返回这些平方数的新数组。不能使用each 以外的任何方法(例如,没有mapcollect)。我尝试设置一个新数组:

def square_array(array)
  array.each do |element|
  new_array = element ** 2
 end 
end

但它返回原始值。帮忙?

【问题讨论】:

  • 仅使用each 是不可能的。为什么不能用其他的?

标签: arrays ruby each


【解决方案1】:

这里还有另一种方法:

[].tap {|result| array.each {|i| result << i ** 2}}

【讨论】:

    【解决方案2】:

    您需要将元素放在一个新数组上并返回它,您只是用当前元素的平方反复创建一个变量 new_array。

    def square_array(array)
        new_array = []
        array.each do |element|
            new_array << element ** 2
        end
        new_array
    end
    
    # shorter
    
    def square_array(array)
        new_array = []
        array.each { |e| new_array << e ** 2 }
        new_array
    end
    
    # even shorter
    
    def square_array(array)
        Array.new(array.size) { |i| array[i] ** 2}
    end
    

    【讨论】:

    • 这里的解决方案使用&lt;&lt;new的方法(除了**)。
    • @sawa 我想人们可以忽略它们,因为它们没有在 array 变量上调用:-/ 尽管第三版 # even shorter 使用 Array#size 方法,如果我们采取可能无效字面上的问题。
    猜你喜欢
    • 1970-01-01
    • 2018-02-03
    • 1970-01-01
    • 1970-01-01
    • 2018-08-26
    • 1970-01-01
    • 2018-12-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多