Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Wrong example or description for "segment" method? #8

Closed
manamski opened this issue Sep 28, 2016 · 3 comments
Closed

Wrong example or description for "segment" method? #8

manamski opened this issue Sep 28, 2016 · 3 comments

Comments

@manamski
Copy link

manamski commented Sep 28, 2016

Why in description of method SEGMENT has two parameters, but one of the examples has three parameters? "->segment('/', 0, true)"

Method description:

/**
 * Get a segment from a string based on a delimiter.
 * Returns an empty string when the offset doesn't exist.
 * Use a negative index to start counting from the last element.
 * 
 * @param string $delimiter
 * @param int $index
 * 
 * @return \Spatie\String\String
 */
public function segment($delimiter, $index)    <-- 2 parameters

Example:
string('foo/bar/baz')->segment('/', 0, true); // baz <-- 3 parameters

Why do not use:
string('foo/bar/baz')->segment('/', -1); // baz

@manamski
Copy link
Author

manamski commented Sep 28, 2016

I think I know myself.
Because there is no value "-0" (for the last element) and string('foo/bar/baz')->segment('/', -1); return before last element "bar" not "baz".
So, why not create a new method "segmentRev($delimiter, $index)", but with positive index counting from the last element?
0 = the last element ("baz")
1 = before last element ("bar")
2 = previous element ("foo")

Edit:
I looked at the source code of the method "lastSegment":

    public function lastSegment($delimiter)
    {
        return (new static($this->string))->segment($delimiter, -1);
    }

...and found that it uses the index with a value "-1". Well, now I don't understand.

@sebastiandedeyne
Copy link
Member

sebastiandedeyne commented Sep 29, 2016

The example with 3 parameters is a mistake, probably a remnant of an older version of the package.

The correct usage is:

string('foo/bar/baz')->segment('/', 0); // 0 returns the first segment
string('foo/bar/baz')->segment('/', 1); // 1 returns the second segment
string('foo/bar/baz')->segment('/', -1); // -1 returns the last segment

(if I'd write this again, I'd probably use a 1-based index, and disallow querying for the 0 segment)

@manamski
Copy link
Author

Thank you for the explanation.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants