Copying strings

W

WoodHacker

I can't believe this hasn't been answered a thousand times, but I can't
seem to find the answer in the group archive.

I am parsing a string into @text (i.e. abc.def) I want to save the
part before the dot into @firstpart . For example:

@text << "a"
@text << "b"
@text << "c" next char is "." so @firstpart = @text
then @text << "."
@text << "d", etc

The problem is, this doesn't work. @firstpart apparently is a
pointer to @text and continues to receive the characters. Freezing
@firstpart doesn't work because then @text << produces a freeze error.
There doesn't appear to be a "copy" method for string, so how do I do
this?

Sometimes the obvious eludes us....

Bill
 
P

Peter Szinek

WoodHacker said:
I can't believe this hasn't been answered a thousand times, but I can't
seem to find the answer in the group archive.

I am parsing a string into @text (i.e. abc.def) I want to save the
part before the dot into @firstpart . For example:

why not

'abc.def'.scan(/(.+)\./)[0]

?

Peter

__
http://www.rubyrailways.com
 
W

William James

WoodHacker said:
I can't believe this hasn't been answered a thousand times, but I can't
seem to find the answer in the group archive.

I am parsing a string into @text (i.e. abc.def) I want to save the
part before the dot into @firstpart . For example:

@text << "a"
@text << "b"
@text << "c" next char is "." so @firstpart = @text
then @text << "."
@text << "d", etc

The problem is, this doesn't work. @firstpart apparently is a
pointer to @text and continues to receive the characters. Freezing
@firstpart doesn't work because then @text << produces a freeze error.
There doesn't appear to be a "copy" method for string, so how do I do
this?

Sometimes the obvious eludes us....

Bill

Your code sample doesn't run at all. Here's one that does.

text = ""
text << "a"
text << "b"
text << "c"
first_part = text.dup
text << "."
text << "d"

p first_part
 
W

WoodHacker

dup did the trick! Thanks a million

bill

William said:
Your code sample doesn't run at all. Here's one that does.

text = ""
text << "a"
text << "b"
text << "c"
first_part = text.dup
text << "."
text << "d"

p first_part
 

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

Forum statistics

Threads
473,769
Messages
2,569,579
Members
45,053
Latest member
BrodieSola

Latest Threads

Top