我一直在做a kata on CodeWars ,其摘要是取一个数字并返回 "Jumping!!"
如果数字在 1 以内(例如 2345
、4323
, 7898
) 和 "Not!!"
否则。所有单个数字(例如 5
、7
、9
)都是跳数。
这是最佳解决方案之一:
def jumping_number(n)
n.to_s.chars.map(&:to_i).each_cons(2).all? { |x, y| (x - y).abs == 1 } ? "Jumping!!" : "Not!!"
end
这是我自己的代码:
def jumping_number(n)
n.to_s.chars.map(&:to_i).each_cons(2) { |x, y| return "Not!!" if (x - y).abs != 1 }
return "Jumping!!"
end
我不明白 each_con
[sic] 是如何工作的。当 n
是单个数字时,这些方法的条件如何(正确)返回 true
? consecutive 是 nil
或 0
,在计算中使用时,不应返回 true
,但它会返回。
最佳答案
这是你的误解:
The consecutive is either nil or 0 which when used in the calculation shouldn't be returning true (and yet it is!)
它既不是nil
也不是0
。它根本不存在。枚举器为空。
不幸的是,这没有记录在the documentation of Enumerable#each_cons
中.你的难题的解决方案是,如果你要求的缺点的大小小于可枚举的大小,那么就不会有缺点:
[5, 6, 7].each_cons(2).to_a
#=> [[5, 6], [6, 7]]
[5, 6, 7].each_cons(3).to_a
#=> [5, 6, 7]
[5, 6, 7].each_cons(4).to_a
#=> []
换句话说:该 block 永远不会执行,因此永远不会有错误。
关于ruby - `each_cons` 如何处理单个数字?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54043312/