Issue #15588 has been updated by osyo (manga osyo).


I also wanted something like `# each_slice`.
For example, use it when you want to fix the width of the output.

```ruby
puts "abcdefghijklmnopqrstuvwxyz".each_slice(5).map { |s| "#{s}<br>" }
# output:
# abcde<br>
# fghij<br>
# klmno<br>
# pqrst<br>
# uvwxy<br>
# z<br>
```

>> Is size in characters or bytes?
> Considering consistency with #slice, it is better to have size as characters.

I think that there may be multiple `String#each_slice_xxx` like` String#each_xxx`.
(e.g. Defined `String#each_slice_byte` , `String#each_slice_char` and more...
Also, I think that `String#each_slice` may be equivalent to`String#each_slice_char`.


----------------------------------------
Feature #15588: String#each_chunk and #chunks
https://bugs.ruby-lang.org/issues/15588#change-80193

* Author: Glass_saga (Masaki Matsushita)
* Status: Open
* Priority: Normal
* Assignee: 
* Target version: 2.7
----------------------------------------
String#each_chunk iterates chunks of specified size in String.
String#chunks is a shorthand for str.each_chunk(n).to_a.

present:
```ruby
str = <<EOS
20190101 20190102
20190103 20190104
EOS

str.scan(/.{1,9}/m) do |chunk|
  p chunk #=> "20190101 "
end

str.scan(/.{1,9}/m) do |chunk|
  chunk.strip!
  p chunk #=> "20190101"
end

str.scan(/.{1,9}/m) #=> ["20190101 ", "20190102\n", "20190103 ", "20190104\n"]
str.scan(/.{1,9}/m).map(&:strip) #=> ["20190101", "20190102", "20190103", "20190104"]
```

proposal:
```ruby
str = <<EOS
20190101 20190102
20190103 20190104
EOS

str.each_chunk(9) do |chunk|
  p chunk #=> "20190101 "
end

str.each_chunk(9, strip: true) do |chunk|
  p chunk #=> "20190101"
end

str.chunks(9) #=> ["20190101 ", "20190102\n", "20190103 ", "20190104\n"]
str.chunks(9, strip: true) #=> ["20190101", "20190102", "20190103", "20190104"]
```

---Files--------------------------------
patch.diff (6.56 KB)


-- 
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>