Undefined method `+@' for false:FalseClass (NoMethodError) ruby

核能气质少年 提交于 2019-12-24 01:24:49

问题


def next_prime_number (last_known_prime)
  while true
    last_known_prime++

    found_factor = false # ERROR
    for i in 1...last_known_prime
      if last_known_prime % i == 0
        found_factor = true
        break
      end
    end
    if !found_factor
      puts "new prime: #{last_known_prime}"
      Kernel.exit
    end
  end
end

in `next_prime_number': undefined method `+@' for false:FalseClass (NoMethodError)

I'm getting the above error and am totally stumped. Any ideas (no, this is not homework, I am trying to teach myself Ruby through the Euler Project).


回答1:


As mikej said, there is no post-increment (++) operator in ruby. There is however, a unary plus (spelled +@ when defining it)

last_known_prime++

found_factor = false

is getting parsed as something like

last_known_prime + (+(found_factor = false))

--------------------^ unary plus on false

which is causing your cryptic error.




回答2:


There is no ++ operator for incrementing an integer in Ruby so try replacing last_known_prime++ with last_known_prime = last_known_prime + 1.

This will fix the error you're seeing. There is another problem with your program after that but I won't spoil your attempt to solve the Euler problem yourself.



来源:https://stackoverflow.com/questions/3548701/undefined-method-for-falsefalseclass-nomethoderror-ruby

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!