“已初始化常数”警告

时间:2017-01-20 09:29:18

标签: ruby

这是我的代码:

puts "Input a number."
Divisor = 2
inputNumber = gets.chomp
if inputNumber.to_i == 1 || inputNumber.to_i == 2
  if inputNumber.to_i == 1
    puts inputNumber + " is not a prime."
  else
    puts inputNumber + " is a prime."
  end
else
  while Divisor.to_i < inputNumber.to_i
    if inputNumber.to_i%Divisor.to_i == 0
      puts inputNumber + " is not a Prime as " + Divisor.to_s + " is a factor."
      break
    else 
      Divisor = Divisor.to_i + 1
    end
  end
  puts inputNumber + " is a prime!"
end

我收到以下错误:

test1.rb:30: warning: already initialized constant Divisor
test1.rb:3: warning: previous definition of Divisor was here

有什么问题?

1 个答案:

答案 0 :(得分:5)

常量和变量

Divisor是常数。你想要一个变量:divisor。请参阅此answer

注释

    始终会调用
  • puts inputNumber + " is a prime!"
  • 您可以将break替换为exit,或使用布尔变量。
  • 由于您使用的是数字,您还可以拨打.to_i一次,进行计算,然后使用.to_s显示结果
  • 您只需检查(2..Math.sqrt(inputNumber))
  • 范围内的因素
  • 如果inputNumber == 1
  • ,您不必检查两次
puts 'Input a number.'
divisor = 2
inputNumber = gets.chomp.to_i
prime = true
if inputNumber == 1
  puts inputNumber.to_s + ' is not a prime.'
else
  while divisor <= Math.sqrt(inputNumber)
    if inputNumber % divisor == 0
      puts inputNumber.to_s + ' is not a Prime as ' + divisor.to_s + ' is a factor.'
      prime = false
      break
    else
      divisor += 1
    end
  end
  puts inputNumber.to_s + ' is a prime!' if prime
end

替代

可以使用Enumerable#find编写更短的替代方案。它使用每个元素执行块,一旦块中的代码返回truthy值就停止,并返回块为真的元素。如果未找到任何元素,则返回nil

puts 'Input a number.'

number = gets.chomp.to_i

divisor = (2..Math.sqrt(number)).find { |i| number % i == 0 }

if number == 1
  puts '1 is not a prime.'
elsif divisor
  puts format('%d is not a prime as %d is a factor.', number, divisor)
else
  puts format('%d is a prime!', number)
end