Issue #12744 has been updated by Bouke van der Bijl.


Martin Drst wrote:
> What about using
> 
> `str.reverse.chars` for `string.reverse_chars`?
> 
> It allocates some memory, but compared to all the memory allocated for the individual characters, the memory for the overall reversed string is not a big deal. Also, it's O(N).
> 
> What's the use case? It doesn't look like a very frequent operation needing a dedicated method if it can be done by method composition so easily.
> 
> Similar for
> `str.reverse_each`, which you probably meant to be `str.reverse_each_line`, which should be something like `string.lines.reverse.each`

I don't really have a use case for reverse_chars, but I added it for symmetry with the other methods. I meant str.reverse_each_char, I typo'd it in the issue but it's correct in the patch. The equivalent with doing allocation would be str.chars.reverse.each. I could use `reverse_each_char` in Sprockets, where we need to iterate over the string backwards to check that it ends with certain characters (and know what it ends with). This needs to be done many times when compiling assets, so having a native way to iterate characters without allocation is a beneficial optimization.

----------------------------------------
Feature #12744: Add str.reverse_each_char and str.reverse_chars
https://bugs.ruby-lang.org/issues/12744#change-60487

* Author: Bouke van der Bijl
* Status: Feedback
* Priority: Normal
* Assignee: 
----------------------------------------
This patch adds `str.reverse_each` and `str.reverse_chars`. It's currently not really possible to iterate a Ruby string in reverse while guaranteeing that you're not accidentally introducing an O(N^2) bug, without encoding to a fixed-length encoding like UTF-32. This is because variable-length encodings like UTF-8 requiring iterating over the whole string if you want to address characters by index.

The patch uses `rb_enc_left_char_head` to iterate over the string in reverse, so you can do so without allocating more memory.

---Files--------------------------------
add-reverse-string-iteration.patch (5.91 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>