2

I found the following code in 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] ??

1 Answer 1

5

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.