Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why isn't there a String#shift()?

Tags:

ruby

I'm working my way through Project Euler, and ran into a slightly surprising omission: There is no String#shift, unshift, push, or pop. I had assumed a String was considered a "sequential" object like an Array, since they share the ability to be indexed and iterated through, and that this would include the ability to easily change the beginning and ends of the object.

I know there are ways to create the same effects, but is there a specific reason that String does not have these methods?

like image 589
wersimmon Avatar asked Feb 10 '11 23:02

wersimmon


2 Answers

Strings don't act as an enumerable object as of 1.9, because it's considered too confusing to decide what it'd be a list of:

  • A list of characters / codepoints?
  • A list of bytes?
  • A list of lines?
like image 161
Andrew Grimm Avatar answered Nov 15 '22 18:11

Andrew Grimm


Not being a Ruby contributor, I can't speak to their design goals, but from experience, I don't think that strings are regarded as 'sequential' objects; they're mutable in ways that suggest sequential behaviour, but most of the time they're treated atomically.

Case in point: in Ruby 1.9, String no longer mixes in Enumerable.

like image 28
dnch Avatar answered Nov 15 '22 18:11

dnch