add text at beginning of a string

F

Fernando Perez

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
 
J

Jesús Gabriel y Galán

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.
 
J

Joel VanderWerf

Phlip said:
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"
 
P

Phlip

irb(main):002:0> s.insert(0, "hello ")

['hello ', s].join

....and how about unshift?

Any sicker ways out there?? Besides s = 'hello ' + s?
 
B

Brian Candler

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"
 
J

Jesús Gabriel y Galán

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.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,578
Members
45,052
Latest member
LucyCarper

Latest Threads

Top