开发者

Use of range in ruby array access

I found the following code i开发者_运维问答n the homebrew code base:

reject{|arg| arg[0..0] == '-'}

Apparently this will remove the element of the array (self) if the element starts with a '-'. My question is why on earth would you need to specify the 0th element of arg in this way, arg[0..0] instead of just specifying arg[0] ??


Because Ruby versions prior to 1.9 return integers (character codes), not characters, from single-element indexing into strings. Like so:

> "abc"[0]
#=> 97
> "abc"[0..0]
#=> "a"
> "abc"[0] == 'a'
#=> false
> "abc"[0..0] == 'a'
#=> true

As of Ruby 1.9, there would be no difference between unsing arg[0..0] and arg[0] in your example.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜