mixing variables and strings

A

arose

How to I mix variables and strings together.

In vb I use the & for example.

firstthree="abc"
firstsix=firstthree & "def"
 
O

OliverMarchand

arose said:
How to I mix variables and strings together.

In vb I use the & for example.

firstthree="abc"
firstsix=firstthree & "def"

For many String concatenations, do *not* use the + operator, rather
collect all the small strings to be concatenated in an array and use
..join("")

-----
n=10000

t = Time.new
str = ""
(0).upto(n) { str += "somestring"}
p Time.new-t


t = Time.new
str = []
(0).upto(n) { str.push("somestring") }
str = str.join("")
p Time.new-t
-----

yields

0.879806
0.038133

The reason is that whenever a string is appended via +, new space must
be made availabe in memory and that leads to subsequent copying of the
whole string. (This is what I assume, I have not looked at the ruby
source code...)

ciao,
Oliver
 
A

arose

thanks everybody

arose said:
How to I mix variables and strings together.

In vb I use the & for example.

firstthree="abc"
firstsix=firstthree & "def"

For many String concatenations, do *not* use the + operator, rather
collect all the small strings to be concatenated in an array and use
.join("")

-----
n=10000

t = Time.new
str = ""
(0).upto(n) { str += "somestring"}
p Time.new-t


t = Time.new
str = []
(0).upto(n) { str.push("somestring") }
str = str.join("")
p Time.new-t
-----

yields

0.879806
0.038133

The reason is that whenever a string is appended via +, new space must
be made availabe in memory and that leads to subsequent copying of the
whole string. (This is what I assume, I have not looked at the ruby
source code...)

ciao,
Oliver
 
C

ChrisH

You can also use substitution:

x='123' #=>'123'
y="#{x}ABC" #=> '123ABC'

Within double-quotes (") you can put code using #{code} and the result
of evaluating the code is put into the string.

Cheers
 

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
474,206
Messages
2,571,069
Members
47,677
Latest member
MoisesKoeh

Latest Threads

Top