Why does this Ruby method return a "void value expression" error?

I have this simple method

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"

When I run it, I get an error void value expressionon line 4, which is the return statement

What is wrong here?

+4
source share
1 answer

I know that this is long overdue, but I noticed that there was no answer to this question, since I was studying this same problem. I got the same error not so long ago that this error means: Ruby is trying to find conditions changeinside your code and cannot find it. This may be because Ruby is not reading your code properly, or it may be because there is an error somewhere. Locking is actually very simple.

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 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

:

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. ( )
  • , .., , -, .
  • , , IE , .

, , , , , , , Linux Windows. , .

+5

All Articles