1

I want to build a string from right to left. My first thought was to use unshift, but String class doesn't have an unshift. What's the most idiomatic way to build a string from right to left?

2 Answers 2

3

Though there's no String#unshift, there is a String#prepend, which would allow you to prepend strings to an existing string.

str = "right"
str.prepend("middle ")
str.prepend("left ")

# left middle right
0
1

I like Michael's answer. Here's another alternative: build an array of substrings from right to left, then call Array#join on it. If you have many substrings, this approach is likely to be faster than the String#prepend approach.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.