test2.rb:15:在`<main>&#39;:未定义的方法`存在?&#39; for&#34; skilldev&#34;:String(NoMethodError)

时间:2018-05-09 05:09:32

标签: ruby

有人请帮我解决这个错误!任何帮助表示赞赏!

username = "skilleddev"

if username.exists?
    puts "Variable 'username' exists."
else
    puts "Variable 'username' does not exist."
end

2 个答案:

答案 0 :(得分:0)

引发错误,因为String对象没有exists?方法。如果要检查是否定义了变量,则应使用defined?方法:

username = "skilleddev"

if defined?(username)
    puts "Variable 'username' exists."
else
    puts "Variable 'username' does not exist."
end

答案 1 :(得分:0)

或者,如果您想知道变量是否为字符串:

username = "skilleddev"

if username.instance_of? String
    puts "Variable 'username' exists as String.."
else
    puts "Variable 'username' does not exist as String."
end