Issue #12304 has been updated by Shyouhei Urabe.

Status changed from Open to Feedback

There are methods like String.each_char.slice_when (and friends). See http://ruby-doc.org/core-2.3.0/Enumerable.html#method-i-slice_when
Doesn't this solve your problem?  Then, can you show us a bit more details about your use case?

----------------------------------------
Feature #12304: String#split with a block
https://bugs.ruby-lang.org/issues/12304#change-58176

* Author: Tsuyoshi Sawada
* Status: Feedback
* Priority: Normal
* Assignee: 
----------------------------------------
I would like `String#split` to take an optional block, similar to `String#scan` with a block.

Suppose I have a regex pattern with captures, and I want to iterate over matches while having access to the information in last match `$~`. In such case, I can use `scan`, and access the last match in the block during iteration:

~~~ruby
"abcabd".scan(/(a)|(b)/) do
  |s|
  if    $1 then ... # `s` is `"a"`, `"a"`
  elsif $2 then ... # `s` is `"b"`, `"b"`
  end
end
~~~

In my use case, I need to iterate over not only the matching patterns, but **also the non-matched substrings in between them**. For such cases, I need to use `split` instead of `scan`. And I would like to do something like the following:

~~~ruby
"abcabd".split(/((a)|(b))/) do
  |s|
  if $2    then ... # `s` is `"a"`, `"a"`
  elsif $3 then ... # `s` is `"b"`, `"b"`
  else ...          # `s` is `"c"`, `"d"`, and `$~` should be `nil`
  end
end
~~~

With the current functionalities, I attempted to do this:

~~~ruby
"abcabd".split(/((a)|(b))/).each do
  ...
end
~~~

but it does not work the way I wanted; within the `each` block, the last match value `$~` is `nil`, and I cannot access the information.



-- 
https://bugs.ruby-lang.org/

Unsubscribe: <mailto:ruby-core-request / ruby-lang.org?subject=unsubscribe>
<http://lists.ruby-lang.org/cgi-bin/mailman/options/ruby-core>