为何HackerRank测试用例中Ruby的#tally方法触发NoMethodError?
问题:Ruby数组#tally方法在HackerRank上触发NoMethodError
我用Ruby解决HackerRank稀疏数组问题时,本地使用Array#tally统计元素出现次数能得到预期结果,但提交代码后触发NoMethodError,提示数组不存在tally方法。
本地测试代码
string_list = ['ab', 'ab', 'abc'] string_count = string_list.tally p string_count: {"ab"=>2, "abc"=>1}
报错信息
Solution.rb:16:in `matchingStrings': undefined method `tally' for ["aba", "baba", "aba", "xzxb"]:Array (NoMethodError) from Solution.rb:45:in `<main>'
完整代码
def matching_strings(string_list, queries) string_count = string_list.tally queries.map do |query| string_count[query].nil? ? string_count[query] = 0 : string_count[query] end end string_list = ['ab', 'ab', 'abc'] queries = ['ab', 'abc', 'bc'] p matching_strings(string_list, queries) : [2, 1, 0]
错误原因
Array#tally是Ruby 2.7版本才正式引入的方法,而HackerRank的Ruby运行环境版本低于2.7,因此不支持这个方法。你的本地开发环境使用了较新的Ruby版本,所以可以正常运行tally方法。
替代实现方案
用each_with_object结合默认值为0的Hash手动实现统计逻辑,兼容低版本Ruby:
def matching_strings(string_list, queries) string_count = string_list.each_with_object(Hash.new(0)) do |str, hash| hash[str] += 1 end queries.map { |query| string_count[query] } end
这里Hash.new(0)会给不存在的键自动返回0,无需额外判断nil值,代码更简洁且兼容所有Ruby版本。
内容的提问来源于stack exchange,提问作者Robert L.
相关产品推荐
相关产品推荐

