Project

General

Profile

Actions

Feature #14783

open

String#chars_at / String#bytes_at

Feature #14783: String#chars_at / String#bytes_at

Added by sos4nt (Stefan Schüßler) over 7 years ago. Updated over 7 years ago.

Status:
Open
Assignee:
-
Target version:
-
[ruby-core:87235]

Description

I just wanted to extract characters at certain indices from a string and noticed that there's no values_at counterpart for String.

I'd therefore like to propose two new String methods:

  • chars_at(selector, ...) → new_str
  • bytes_at(selector, ...) → new_str

which work basically like Array#values_at, e.g.:

string = 'hello, world!' string.chars_at(0, 5, 7, 12) #=> "h,w!"  string.chars_at(0..4, 7..11) #=> "helloworld"  

Updated by Hanmac (Hans Mackowiak) over 7 years ago Actions #1 [ruby-core:87236]

@sos4nt

why does it return a new string instead of array of strings?

you might like this:

string = 'hello, world!' [0, 5, 7, 12].map(&string.method(:[])).join #=> "h,w!" [0..4, 7..11].map(&string.method(:[])).join #=> "helloworld" 

Updated by zverok (Victor Shepelev) over 7 years ago Actions #2 [ruby-core:87237]

string = 'hello, world!' string.chars.values_at(0, 5, 7, 12) # => ["h", ",", "w", "!"] string.chars.values_at(0, 5, 7, 12).join # => "h,w!"  

¯\_(ツ)_/¯

Updated by sos4nt (Stefan Schüßler) over 7 years ago Actions #3 [ruby-core:87238]

Hanmac (Hans Mackowiak) wrote:

why does it return a new string instead of array of strings?

Because String#[] also returns a string in such case:

a = [1, 2, 3, 4] s = "1234" a[1..2] #=> [2, 3] s[1..2] #=> "23" 

Accordingly:

a.values_at(1..2) #=> [2, 3] s.chars_at(1..2) #=> "23" 

Updated by nobu (Nobuyoshi Nakada) over 7 years ago Actions #4 [ruby-core:87249]

sos4nt (Stefan Schüßler) wrote:

Because String#[] also returns a string in such case:

It's a different, single argument case.
I don't think that values_at should return same class as the receiver, as Hash#values_at.

Updated by shevegen (Robert A. Heiler) over 7 years ago Actions #5 [ruby-core:87252]

Is the frequency of #bytes_at common? I understand the use case
stated by Stefan (extract multiple indices via one method call
on a String) but #bytes_at may seem to be quite rare.

As for returning a String or Array, I personally expect #chars
on a String object to return an Array, so intuitively I would
assume #chars_at to also return an Array.

Actions

Also available in: PDF Atom