Why isn't there a String#shift()?
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?
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?
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
.
>> mystring = "abcdefgh"
=> "abcdefgh"
>> myarray = mystring.split("")
=> ["a", "b", "c", "d", "e", "f", "g", "h"]
>> myarray.pop
=> "h"
>> mystring = myarray.join
=> "abcdefg"
this should do it, you wouldhave to convert it to an array, and then back though
UPDATE:
use String#chop!
and Stirng#<<
>> s = "abc"
=> "abc"
>> s.chop!
=> "ab"
>> s
=> "ab"
>> s<<"def"
=> "abdef"
>> s
=> "abdef"
>>
Well at least in 1.9.2, you can deal with a string like an array.
ruby-1.9.2-p290 :001 > "awesome"[3..-1] => "some"
So if you want to do a sort of character left shift, just use [1..-1]
ruby-1.9.2-p290 :003 > "fooh!"[1..-1] => "ooh!"
精彩评论