我有这个简单的方法
def is_palindrome?(sentence)
raise ArgumentError.new('expected string') unless sentence.is_a?(String)
safe_sentence = sentence.gsub(/\W+/, '').downcase
return safe_sentence == safe_sentence.reverse
end
is_palindrome?"rails"
当我运行它时,第 4 行出现错误 void value expression
,这是返回语句
这是怎么回事?
最佳答案
我知道这早就应该了,但我注意到这个问题没有答案,因为我正在研究这个完全相同的问题。不久前我遇到了同样的错误,这个错误意味着 Ruby 试图在你的代码中找到一个 conditions change
但找不到它。这可能是因为 Ruby 没有正确读取您的代码,或者可能是因为某处存在错误。修复它实际上非常容易。
def is_palindrome?(sentence)
raise ArgumentError.new('expected string') unless sentence.is_a?(String)#<= Right here at 'unless' condition is changed
safe_sentence = sentence.gsub(/\W+/, '').downcase
return safe_sentence == safe_sentence.reverse
end
is_palindrome?"rails"
出于某种原因,您的 Ruby 版本试图找到条件更改并默认为原始条件,需要大量研究才能得出这个。
那么如何解决这个问题呢?快速的答案是添加 if/else 语句
而不是 unless
:
def is_palindrome?(word)
to_rev = word.split('')
rev_arr = to_rev.reverse
new_word = rev_arr.join('')
if new_word == word
return true
else
return false
end
end
is_palindrome?("racecar") #<= Returns true
is_palindrome?("test") #<= Returns false
如果您想使用正则表达式:
def is_palindrome?(sentence)
new_sentence = sentence.gsub(/\W+/, '').downcase.reverse
if new_sentence == sentence.downcase
return true
elsif new_sentence != sentence.downcase
return false
else
raise ArgumentError.new("String expected, instead found #{sentence}")
end
end
is_palindrome?("racecar") #<= Returns true
is_palindrome?("test") <= Returns false
这完全未经测试,但您明白了。这将添加条件变化,并允许 Ruby 意识到条件发生了变化。
现在为什么你的系统输出这个?再次简短的回答是,没有人真正知道,可能是您的系统中有错误,可能是您的某个地方的 Ruby 版本已损坏。
您可以尝试的几件事:
- 重新安装最新版本的 Ruby
- 进入系统中的 Ruby 文件并检查任何不属于的内容
- 将您的目录移动到保证与 Ruby 一起运行的某个地方,IE 进入 Ruby 目录本身。 (这真的不应该成为问题)
- 检查您的 CPU 使用率、正在运行的程序等,看看是否有任何可能会干扰您的系统
- LAST RESORT 硬重启您的系统,除非绝对必要,否则不要执行此操作,IE 会发现不重启就无法清除的病毒。
人们无法重现此错误的原因可能是因为没有人能够真正看到您运行程序的方式,也许您使用的是不同版本的 Linux 或 Windows,等等。希望这能回答您的问题..
关于ruby - 为什么这个 Ruby 方法会返回 "void value expression"错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29022537/