如何在没有 `each` `map` 或 `collect` 方法的情况下对 ruby 中的数字数组求平方?

How to square an array of numbers in ruby with while without `each` `map` or `collect` methods?

我是 RUBY 中的编码新手。我正在尝试编写一种方法,对数字数组中的每个元素进行平方和 returns 这些数字平方的新数组。尝试使用 while 循环而不是使用 eachcollectmap。难以理解如何 index/loop 数组和正方形的每个单独元素是 (**)。

这对我来说是有意义的,但我知道这是错误的。

def square_array(numbers)
  count = 0
  while count < numbers.length do
    numbers.index ** 2 
  end
  square_array(numbers)
end 

有人能帮帮我吗?谢谢!

最简单的方法是map,当然:

def square_array(numbers)
    numbers.map { |e| e ** 2 }
end 

但要使用 while 循环执行同样的操作(这是很好的做法),您必须执行以下操作。

  1. 创建一个数组来包含转换后的数据。
  2. 创建一个计数器(您已经完成了)。
  3. 设置你的 while 循环(正如你所拥有的,除了你不需要最后的 do)。
  4. 编写一个语句,对索引与您的计数器相同的数组元素求平方,并将结果推送到您在步骤 1 中创建的数组中。
  5. 将你的计数器加 1(你忘了这样做,所以你会得到一个无限循环,因为 count 总是等于 0)。
  6. Return 您在步骤 1 中创建的数组。

这会为你做!看看你能不能把它们放在一起,而不是我只给你代码。

def square_array(numbers)
  # Allocate an array with the same size as `numbers`
  # so that the runtime does not have to resize it from time to time
  result = Array.new(numbers.size)

  # The index
  i = 0

  while i < numbers.size
    # Fill the result array
    result[i] = numbers[i] ** 2

    # and don't forget to increase the index,
    # otherwise the loop will run forever.
    i += 1
  end

  # Return the result array
  result
end

更实用的方法是使用递归。

fun =
  ->(acc = [], arr, map, fun) {
    arr.empty? ? acc : fun.(acc << map.(arr.shift), arr, map, fun)
  }
#⇒ #<Proc:0x000055ab64333fa0@(pry):12 (lambda)>

对于任何映射器(例如平方根),请像这样使用它:

fun.([1,2,3,4,5], ->(e) { e ** 2 }, fun)
#⇒ [1, 4, 9, 16, 25]

请注意!这种方法 改变 初始数组,因此在传递给函数之前应该明确 array.dup 。为了消除通过 传递函数本身并 保持初始数组不变的必要性,我们需要一个包装器。

fun =
  ->(acc = [], arr, map, fun) {
    arr.empty? ? acc : fun.(acc << map.(arr.shift), arr, map, fun)
  }
#⇒ #<Proc:0x000055ab64333fa0@(pry):12 (lambda)>
mapper = ->(arr, map) { fun.([], arr.dup, map, fun) }

并像这样使用它:

arr = [1,2,3,4,5]
mapper.(arr, ->(e) { e ** 2 })
#⇒ [1, 4, 9, 16, 25]
arr
#⇒ [1, 2, 3, 4, 5]
def sq(arr)
  enum = arr.each
  a = []
  loop do
    n = enum.next
    a << n*n
  end
  a
end

sq [1, 2, 3, 4]
  #=> [1, 4, 9, 16]

参见 Array#each, Kernel#loop and Enumerator#next. One could use Kernel#to_enum (documented in Object) 代替 Array#each

使用 for 循环?

ary = [1,2,3]

res = []
for n in ary do
  res << n ** 2
end

res
#=> [1, 4, 9]

但最好坚持使用 map

这是我的解决方案:

def square_array(numbers)
  new_array = []
  counter = 0 
  while counter < numbers.length()
  new_array.push(numbers[counter] * numbers[counter])
  counter += 1
  end 
  return new_array
end

不使用 each、map 或 collect。

def square_array(array)
 new_array = []
  array.length.times do |index|
  new_array.push(array[index] ** 2)
  end
 new_array
end