Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby: String no longer mixes in Enumerable in 1.9

So how can I still be able to write beautiful code such as:

'im a string meing!'.pop

Note: str.chop isn't sufficient answer

like image 721
Zombies Avatar asked Dec 08 '22 04:12

Zombies


2 Answers

It is not what an enumerable string atually enumerates. Is a string a sequence of ...

  • lines,
  • characters,
  • codepoints or
  • bytes?

The answer is: all of those, any of those, either of those or neither of those, depending on the context. Therefore, you have to tell Ruby which of those you actually want.

There are several methods in the String class which return enumerators for any of the above. If you want the pre-1.9 behavior, your code sample would be

'im a string meing!'.bytes.to_a.pop

This looks kind of ugly, but there is a reason for it: a string is a sequence. You are treating it as a stack. A stack is not a sequence, in fact it pretty much is the opposite of a sequence.

like image 184
Jörg W Mittag Avatar answered Dec 20 '22 09:12

Jörg W Mittag


That's not beautiful :)

Also #pop is not part of Enumerable, it's part of Array.

The reason why String is not enumerable is because there are no 'natural' units to enumerate, should it be on a character basis or a line basis? Because of this String does not have an #each

String instead provides the #each_char and #each_byte and #each_line methods for iteration in the way that you choose.

like image 27
horseyguy Avatar answered Dec 20 '22 10:12

horseyguy