Add text at beginning of a string

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

On Sat, Dec 20, 2008 at 6:13 PM, Fernando P. [email protected]
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.

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

['hello ', s].join

…and how about unshift?

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

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”

On Sat, Dec 20, 2008 at 9:26 PM, Phlip [email protected] 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.

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”

I had the exact same question in mind. I googled for a very efficient solution that will not change the object_id of the variable. You can also use constants.
Since a lot has changed since then, let’s update the reply to help others.
I can think of three ways. Here are the codes:

a = ?d                         # => "d"
p a.object_id                  # => 3866916

a.prepend('hello worl')        # => "hello world"
p a                            # => "hello world"
p a.object_id                  # => 3866916

a.replace ?d                   # => "d"

# Using the bracket syntax     # => nil
p a[0, 0] = 'hello worl'       # => "hello worl"
p a                            # => "hello world"
p a.object_id                  # => 3866916

a.replace ?d                   # => "d"

# Using the insert method      # => nil
p a.insert(0, 'hello worl')    # => "hello world"
p a                            # => "hello world"
p a.object_id                  # => 3866916