Ruby程序创建接受整数的even_odd方法



我需要帮助编写接受整数数组的even_odd方法。

  1. 它应该返回一个由2个数组组成的数组
  2. 第一个嵌套数组应该只包含奇数
  3. 第二个嵌套数组应仅包含偶数
  4. 如果没有偶数或奇数,则相应的内部数组应为空

输出应该如下所示:-

even_odd([3, 5, 8, 2, 4, 6])
[[3, 5], [2, 4, 6, 8]]
even_odd([3, 5])
[[3, 5], []]
even_odd([2, 4])
[[], [2, 4]]

我是ruby编程的新手,我尝试过以下内容,但没有得到结果:-

def even_odd(numbers)
arr1, arr2 = []
idx = 0
while idx < numbers.length
if numbers[idx] % 2 == 0
puts arr1[idx]   
elsif 
puts arr2[idx]
end
idx += 1
end
end
puts even_odd([2, 3, 6])

错误:-

main.rb:6:in `even_odd': undefined method `[]' for nil:NilClass (NoMethodError)
from main.rb:13:in `<main>'

我会做这个

def even_odd(numbers)
numbers.sort.partition(&:odd?)
end
even_odd([3, 5, 8, 2, 4, 6])
# => [[3, 5], [2, 4, 6, 8]]
even_odd([3, 5])
# => [[3, 5], []]
even_odd([2, 4])
# => [[], [2, 4]]

puts是ruby中的print语句,而不是append语句。它也不运行函数/方法。您还需要调用if…else块内数字数组的索引。

这应该会奏效:

def even_odd(numbers)
arr1, arr2 = [], []
idx = 0
while idx < numbers.length
if numbers[idx] % 2 == 0
arr1 << numbers[idx]
elsif 
arr2 << numbers[idx]
end
idx += 1
end
return arr1, arr2
end
arrays = even_odd([2, 3, 6])
puts arrays

最新更新