5 ms·
rand(1..10) is now possible, cool! Also: 'est'.prepend('t') == 'test' might be useful.
by phzbOx 15y ago
rand(1..10)
is now possible, cool!
Also:
'est'.prepend('t') == 'test'
might be useful.
- trebor 15y agoWhy is "est".prepend('t') more useful than "t" + "est" ? I don't see why a method for prepending to a string is necessary, when it is so simple anyway... And random with a range parameter is useful shorthand. Anyway, I'm more enthusiastic about performance improvements where file loading is concerned.
- phzbOx 15y agoSometime it's easier to chain with other functions and, depending of the situation, it might make the code easier to read.
- yxhuvud 15y agoMore useful? It does a different thing, just like String#+ doesn't do the same thing as String <<. They are not exchanges for each other. Rather - they are complements.
- minikomi 15y agoNot to mention more verb like - and thus descriptive.
- petercooper 15y agoFirst, let's say you subclassed String or have a delegate. obj.prepend(str) will adjust obj in place rather than create an all new String object (as str + obj would). This may be either desirable or critical, depending on what you're doing. Second, prepend is a lot faster than using + in this case. As in, a simple prepend runs in a mere 1.9% of the time (in a benchmark I just ran). Why? Fewer new objects are being created. And that means easier and fewer GC runs too. Update: I think there is something slightly bust since on 1.9.2 using + handily beats prepend on 1.9.3. But GC has changed a lot. I'll retest on RC1 rather than preview1 ;-)
- trebor 15y agoGood point; I did not consider conserving objects and the overhead of allocation/initialization versus reallocation.
- getsat 15y ago#prepend replaces in place? There's no #prepend! ?
- yxhuvud 15y agoThat would be redundant, since there would be no difference from String#+.
- petercooper 15y agoNo. Conventionally, "bang" methods should only be created as 'dangerous' versions of non-bang methods. There was no non-bang method to make a 'dangerous' version of in this case so it's non-bang by default. This is a commonly misunderstood naming convention in Ruby (and I dare say I don't even understand all the intricacies!) There are quite a few examples of this in Ruby. For example, Array#keep_if which changes an array in place.
- getsat 15y agoI guess I misunderstood your definition of "in place". That jives with what I've understood about Ruby so far.
- dkubb 15y agoHow does String#prepend compare to String#insert in your benchmarks? eg. "bc".insert(0, "a") # => "abc"