ruby - `each_cons` 如何处理单个数字?

标签 ruby

我一直在做a kata on CodeWars ,其摘要是取一个数字并返回 "Jumping!!" 如果数字在 1 以内(例如 23454323 , 7898) 和 "Not!!" 否则。所有单个数字(例如 579)都是跳数。

这是最佳解决方案之一:

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 是 nil0,在计算中使用时,不应返回 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/

相关文章:

ruby-on-rails - 如何彻底删除并重新创建thinking-sphinx索引?

ruby-on-rails - 如何正确使用 `return` 为 `render` : DoubleRenderError

ruby - !foo = 表达式在 Ruby 中合法吗?

ruby-on-rails - ruby rails : pass params to link_to to call the create path

jquery - Ruby on Rails 项目时间选择器

ruby-on-rails - 按子域过滤 ruby​​ on rails 中的数据

ruby - ' +' can' t 将 Fixnum 转换为字符串 (TypeError)

Ruby:如何在保留分隔符的同时拆分正则表达式上的字符串?

ruby - Grape API 和 HTTP 摘要身份验证

ruby - Rails 3 runner 没有检测到 JSON gem?