为什么这个Ruby代码没有返回预期的答案?

TCS*_*rad 1 ruby

我正在使用以下方法尝试列出所有数字因子:

def find_factors(n)
  factors = []
  2.upto(n-1) {|x| factors << x if n % x == 0}
end

factor = find_factors(24)
puts factor
Run Code Online (Sandbox Code Playgroud)

它打印出以下内容:

2
Run Code Online (Sandbox Code Playgroud)

而不是因素列表!如果做错了怎么办?

saw*_*awa 5

upto与块一起使用返回接收器,即2.

写这个的更好方法是:

def find_factors(n)
  2.upto(n-1).select{|x| (n % x).zero?}
end
Run Code Online (Sandbox Code Playgroud)