为什么这个Ruby方法返回"void value expression"错误?

Ahm*_*eat 4 ruby

我有这个简单的方法

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"
Run Code Online (Sandbox Code Playgroud)

当我运行它时,我void value expression在第4行得到错误,这是return语句

这有什么不对?

13a*_*aal 5

我知道这是姗姗来迟的,但我注意到这个问题没有答案,因为我正在研究这个完全相同的问题.我很久以前就遇到了同样的错误,这个错误意味着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"
Run Code Online (Sandbox Code Playgroud)

由于某种原因,你的Ruby版本试图找到条件变化并默认为原始状态,因此需要进行大量研究才能得出结论.

那你怎么解决这个问题呢?快速回答是添加一个if/else statement而不是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
Run Code Online (Sandbox Code Playgroud)

如果你想使用你的正则表达式:

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
Run Code Online (Sandbox Code Playgroud)

这是完全未经测试但你明白了.这将增加条件的变化,并允许Ruby意识到条件发生了变化.


现在为什么你的系统输出这个?简短的回答是,没有人真正知道,可能是你的系统中有一个错误,可能是你的某个版本的Ruby已经损坏了.

您可以尝试几件事:

  1. 重新安装最新版本的Ruby
  2. 进入系统中的Ruby文件并检查不属于的任何内容
  3. 将您的目录移动到保证与Ruby,IE一起运行到Ruby目录本身的某个地方.(这真的不应该是一个问题)
  4. 检查您的CPU使用情况,运行程序等,看看是否有任何可能弄乱您的系统
  5. 最后的调度硬重启你的系统不要这样做,除非你绝对不得不,IE你发现一个无法重新启动无法擦除的病毒.

人们无法重现这个错误的原因可能是因为没有人能真正看到你运行程序的方式,也许你有不同版本的Linux或Windows,无论如何.希望这能回答你的问题..