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

sevk · November 15, 2018 · Last by heroyct replied at November 15, 2018 · 1322 hits
p (1..10).size  
p ('a'..'z').size

其它语言也这样处理吗?

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

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

Reply to 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
You need to Sign in before reply, if you don't have an account, please Sign up first.