Project

General

Profile

Feature #14783

String#chars_at / String#bytes_at

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

Status:
Open
Priority:
Normal
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" 

History

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

sos4nt (Stefan Schüßler)

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"

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

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

¯\_(ツ)_/¯

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

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"

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

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.

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

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.

Also available in: Atom PDF