红宝石计数笑脸 - 退出代码 = 1



Codewars上的计数笑脸问题,我的代码通过了所有测试,但是不断弹出"退出代码= 1"错误消息,这是什么意思?出了什么问题?

countSmileys([':)', ';(', ';}', ':-D']);       // should return 2;
countSmileys([';D', ':-(', ':-)', ';~)']);     // should return 3;
countSmileys([';]', ':[', ';*', ':$', ';-D']); // should return 1;
def count_smileys(arr)
first = ";:"
second = "-~"
third = ")D"
arr.select{|x|
third.include?(x[1]) or (second.include?(x[1]) && third.include?(x[2].to_s)) 
}.count
end

编辑:错误消息如下:

main.rb:8:in `include?': no implicit conversion of nil into String (TypeError)
from main.rb:8:in `block in count_smileys'
from main.rb:7:in `select'
from main.rb:7:in `count_smileys'
from main.rb:16: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:11:in `<main>'

如消息所述,没有将 nil 隐式转换为字符串。不过,显式确实存在:

2.3.1 :001 > nil.to_s
=> "" 

您可以先解析数组以获取nil,然后通过select方法对其进行分析。

def count_smileys(arr)
first = ";:"
second = "-~"
third = ")D"
# parse your array for nil values here
arr.map {|x| x.nil? ? "" : x }
arr.select{|x|
third.include?(x[1]) or (second.include?(x[1]) && third.include?(x[2].to_s)) 
}.count
end

我意识到问题是什么 - 有一个测试count_smileys([";", ")", ";*", ":$", "8-D"])其中 x[1] 和 x[2] 对数组中的前 2 个项目无效,所以我需要在 select 方法中修复数组:

def count_smileys(arr)
first = ";:"
second = "-~"
third = ")D"
arr.select{|x|
x[1] = " " if x[1] == nil
x[2] = "" if x[2] == nil
(first.include?(x[0]) && third.include?(x[1])) || (first.include?(x[0]) && second.include?(x[1]) && third.include?(x[2])) 
}.count
end

Joseph Cho 是正确的,因为 nils 需要转换,但我们应该在迭代中这样做,公共项目 x[1] 应该设置为带有空格的空字符串以避免被计数,而 x[2] 不常见到空字符串可以工作。

相关内容

最新更新