关于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>'
答案 0 :(得分:0)
如消息所述,没有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
答案 1 :(得分:0)
我意识到问题出在哪里-有一个测试count_smileys([";", ")", ";*", ":$", "8-D"])
,其中x [1]和x [2]对于数组的前2个项无效,因此我需要在内部修复该数组选择方法:
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
在需要转换nil的意义上,Joseph Cho是正确的,但是我们应该在迭代中进行转换,并且应该将公共项x [1]设置为带有空格的空字符串,以避免被计数,而x [2]很少见,以至于空字符串都可以工作。