我正在研究一个问题,我想逐个字符地比较两个长度相等的字符串。对于字符不同的每个索引,我需要将计数器加 1。现在我有这个:
def compute(strand1, strand2)
raise ArgumentError, "Sequences are different lengths" unless strand1.length == strand2.length
mutations = 0
strand1.chars.each_with_index { |nucleotide, index| mutations += 1 if nucleotide != strand2[index] }
mutations
end
end
我是这门语言的新手,但对我来说这感觉非常非 Ruby。是否有一个单行程序可以合并设置计数器、递增它然后返回它的过程?
我的思路是选择所有不匹配的字符,然后获取结果数组的大小。但是,据我所知,没有 select_with_index
方法。我也在研究 inject
但似乎无法弄清楚我将如何在这种情况下应用它。
最佳答案
可能最简单的答案就是计算差异:
strand1.chars.zip(strand2.chars).count{|a, b| a != b}
关于ruby - 设置计数器、递增和返回的更简洁的方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30809093/