Forum: Ruby add text at beginning of a string

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
059ed46172a087063ce26250e44c8627?d=identicon&s=25 Fernando Perez (fernando)
on 2008-12-20 18:21
Hi,

Sorry for this silly question, but I don't remember how to insert text
to the beginning of a string. It's like the concatenate (or <<) operator
but it adds text before.


Thanks
E088bb5c80fd3c4fd02c2020cdacbaf0?d=identicon&s=25 Jesús Gabriel y Galán (Guest)
on 2008-12-20 18:33
(Received via mailing list)
On Sat, Dec 20, 2008 at 6:13 PM, Fernando Perez <pedrolito@lavache.com>
wrote:
> Hi,
>
> Sorry for this silly question, but I don't remember how to insert text
> to the beginning of a string. It's like the concatenate (or <<) operator
> but it adds text before.

I recommend studying this page, it's good to be familiar with the
methods in class String:

http://ruby-doc.org/core/classes/String.html

The one you are looking for is:

irb(main):001:0> s = "world"
=> "world"
irb(main):002:0> s.insert(0, "hello ")
=> "hello world"
irb(main):003:0> s
=> "hello world"

Hope this helps,

Jesus.
Aafa8848c4b764f080b1b31a51eab73d?d=identicon&s=25 Phlip (Guest)
on 2008-12-20 21:36
(Received via mailing list)
> irb(main):002:0> s.insert(0, "hello ")

['hello ', s].join

...and how about unshift?

Any sicker ways out there?? Besides s = 'hello ' + s?
47b1910084592eb77a032bc7d8d1a84e?d=identicon&s=25 Joel VanderWerf (Guest)
on 2008-12-20 21:40
(Received via mailing list)
Phlip wrote:
>> irb(main):002:0> s.insert(0, "hello ")
>
> ['hello ', s].join
>
> ...and how about unshift?
>
> Any sicker ways out there?? Besides s = 'hello ' + s?

irb(main):001:0> s = " world"
=> " world"
irb(main):002:0> s[/\A/] = "hello,"
=> "hello,"
irb(main):003:0> s
=> "hello, world"
753dcb78b3a3651127665da4bed3c782?d=identicon&s=25 Brian Candler (candlerb)
on 2008-12-21 23:08
>> Any sicker ways out there?? Besides s = 'hello ' + s?

irb(main):001:0> s = " world"
=> " world"
irb(main):002:0> s[0,0] = "hello"
=> "hello"
irb(main):003:0> s
=> "hello world"
E088bb5c80fd3c4fd02c2020cdacbaf0?d=identicon&s=25 Jesús Gabriel y Galán (Guest)
on 2008-12-22 09:09
(Received via mailing list)
On Sat, Dec 20, 2008 at 9:26 PM, Phlip <phlip2005@gmail.com> wrote:
>> irb(main):002:0> s.insert(0, "hello ")
>
> ['hello ', s].join
>
> ...and how about unshift?
>
> Any sicker ways out there?? Besides s = 'hello ' + s?

Just a note: both your join method and the + method above will create
a new string object, while the other methods in this thread (insert,
[/\A/], [0,0]) will modify the string in place. This might or might
not matter to the OP.

Regards,

Jesus.
This topic is locked and can not be replied to.