# Can't understand String#split's behavior

**URL:** <https://www.ruby-forum.com/t/cant-understand-string-splits-behavior/197602>\
**Category:** Ruby\
**Created:** [October 17, 2010, 2:52am UTC](https://www.ruby-forum.com/t/cant-understand-string-splits-behavior/197602 "2010-10-17T02:52:36Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![Dobai-Pataky\_BSSSSl](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/d/77aa72/32.png) [@Dobai-Pataky\_BSSSSl](https://www.ruby-forum.com/u/Dobai-Pataky_BSSSSl)\
**Post date:** [October 17, 2010, 2:52am UTC](https://www.ruby-forum.com/t/cant-understand-string-splits-behavior/197602/1 "2010-10-17T02:52:36Z")

</div>

When I use ruby 1.8.7 I have a problem with String#split.

It’s fine:

> > p “bAbAbAb”.split(/A/)  
> > [“b”, “b”, “b”, “b”]

But it cant work:

> > p “bAbAbAb”.split(/(A)/)  
> > [“b”, “A”, “b”, “A”, “b”, “A”, “b”]

I think that /A/ and /(A)/ are almost equivalent, but why can’t I use  
/(A)/  
to split string?

-Lai

---

<div class="post-metadata">

**Author:** ![SSSSSSSSSS\_SSS](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/s/dfb087/32.png) [@SSSSSSSSSS\_SSS](https://www.ruby-forum.com/u/SSSSSSSSSS_SSS)\
**Post date:** [October 17, 2010, 4:42am UTC](https://www.ruby-forum.com/t/cant-understand-string-splits-behavior/197602/2 "2010-10-17T04:42:21Z")

</div>

On Sun, Oct 17, 2010 at 8:46 AM, 冷雨 [removed\_email\_address@domain.invalid](mailto:removed_email_address@domain.invalid) wrote:

> I think that /A/ and /(A)/ are almost equivalent,

almost

> but why can’t I use /(A)/ to split string?

as documented, you can, but w a different behaviour/result for split

## (from ruby core) === Implementation from String

str.split(pattern=$;, [limit]) → anArray

* * *

Divides str into substrings based on a delimiter, returning an array of  
these substrings.

If pattern is a String, then its contents are used as the  
delimiter when splitting str. If pattern is a single  
space, str is split on whitespace, with leading whitespace and runs of  
contiguous whitespace characters ignored.

If pattern is a Regexp, str is divided where the pattern  
matches. Whenever the pattern matches a zero-length string, str is split  
into individual characters. If pattern contains groups, the  
respective matches will be returned in the array as well.  
…

---

<div class="post-metadata">

**Author:** ![SSSSSSSSSS\_SSS](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/s/dfb087/32.png) [@SSSSSSSSSS\_SSS](https://www.ruby-forum.com/u/SSSSSSSSSS_SSS)\
**Post date:** [October 17, 2010, 5:59am UTC](https://www.ruby-forum.com/t/cant-understand-string-splits-behavior/197602/3 "2010-10-17T05:59:37Z")

</div>

Sorry for my careless.  
And thank you very match.
