[英]Pushing numbers onto an array in Ruby
I'm trying to create a program outputting each number and whether it is divisible by numbers 2-9. 我正在尝试创建一个输出每个数字以及是否可以被数字2-9整除的程序。 I'm doing this by iterating over 2-9 and pushing each number onto an array, however, an error shows up when compiling: 我这样做是通过迭代2-9并将每个数字推入数组来进行的,但是,编译时会出现错误:
/Users/XXX/XXX/XXX/XXX.rb:3: warning: already initialized constant ArrayOfMultiples
How do I remove this error? 如何清除此错误?
Here is my code: 这是我的代码:
(1..200).each do |number|
output_str = ""
ArrayOfMultiples = Array.new
(2..9).each do |multiple|
if number%multiple == 0
ArrayOfMultiples.push(multiple)
end
end
output_str = number.to_s + " is divisble by " + ArrayOfMultiples.join(", ")
puts output_str
end
Start your variable with lower case, otherwise it is considered a constant. 以小写字母开头的变量,否则视为常量。 If you reinitialize a constant, you get that warning. 如果重新初始化常量,则会收到该警告。
arrayOfMultiples
A simple program like the following can demonstrate this behaviour: 像下面这样的简单程序可以演示这种行为:
A = 1
A = 2
When you run the above script, it says: 当您运行上面的脚本时,它说:
test.rb:2: warning: already initialized constant A
test.rb:1: warning: previous definition of A was here
You could also make this a lot simpler: 您还可以使它变得更简单:
(1..200).each do |x|
divisible_by = (2..9).select {|y| x%y==0}
puts "#{x}: #{divisible_by.join(", ")}"
end
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.