Ruby 同样是 Range , 为啥后者没有 size ?

sevk · 2018年11月15日 · 最后由 heroyct 回复于 2018年11月15日 · 1318 次阅读
p (1..10).size  
p ('a'..'z').size

其它语言也这样处理吗?

"00:01".."12:34"

如果有的话,这个的 size 应该是多少呢

lukertty 回复
[6] pry(main)> ("00:01".."12:34").to_a.size
=> 1234

其它语言应该都是这样吧? https://play.crystal-lang.org/#/r/5ixe 可以统计一下

源码有注释,开头和结尾必须都是数字才返回 size

Both the begin and the end of the Range must be Numeric, otherwise nil is returned.

# rng.size                   -> num
# 
# Returns the number of elements in the range. Both the begin and the end of
# the Range must be Numeric, otherwise nil is returned.
# 
#   (10..20).size    #=> 11
#   ('a'..'z').size  #=> nil
#   (-Float::INFINITY..Float::INFINITY).size #=> Infinity
def size()
    #This is a stub, used for indexing
end
需要 登录 后方可回复, 如果你还没有账号请 注册新账号