I've been trying to solve this Codewars problem with Ruby but it keeps giving me this error and I don't know the reason.
main.rb:10:in `head_smash': undefined method `each' for "":String (NoMethodError)
from main.rb:80:in `block in <main>'
from /runner/frameworks/ruby/cw-2.rb:55:in `block in describe'
from /runner/frameworks/ruby/cw-2.rb:46:in `measure'
from /runner/frameworks/ruby/cw-2.rb:51:in `describe'
from main.rb:17:in `<main>'
My code to solve this problem is this one:
def head_smash(arr)
arr1 = []
if arr == []
return 'Gym is empty'
elsif arr.is_a?(Integer) == true
return 'This isn\'t the gym!!'
else
arr.each do |i|
arr1.append(i.gsub(/O/, ' '))
end
end
return arr1
end
How can I solve this?
It is probably this test (see line #64 in the test for that exercise) that makes your code fail:
Test.assert_equals(head_smash(''),'Gym is empty')
In that test, the input is an empty String
but your code doesn't check for string types and at least handles empty Strings. Instead, your code calls arr.each
when arr
is a string.
A very simple approach to fix this specific issue would be to change the first condition
if arr == []
to any of the following
if arr == [] || arr == ''
if [[], ''].include?(arr)
if arr.respond_to?(:empty?) && arr.empty?