I have a string which I would like to serialize and deserialize. This one for instance:
"hello, world"
Now, if I find-and-replace (dump step) every world
sub-string by o
, this string become:
"hello, o"
But, if I try to find-and-replace again i开发者_如何转开发n the other way from o
to world
(load step), this string become:
"hellworld, world"
...which is not the same as the first string. Is there a easy way to handle this, escaping chars, with Ruby 1.9.2?
Thank you!
EDIT:
In other words, I would be able to:
- Replace a parameter (for example "
world
") in a text by a value (for example "o
"). - Replace any values ("
o
", according to the example) by the parameter ("world
", according to the example)
So I would like to be able to do so (with something like dump()
and load()
methods):
string = "Hello world, Ruby on Rails 3.1.0 is out! Yay!"
serialized_string = dump(string)
# => "Hell\o o, Ruby \on Rails 3.1.0 is \out! Yay!"
load(serialized_string).should == string # => true
Thanks for any idea :)
Out of curiosity, why are you doing this? This has not much to do with ruby, but with regular expressions.
Anyway, wouldn't it be easier to store the original string, so that you can restore it?
Alternatively, if you only want to match the last o
, try to use the pattern o$
.
But I really think you should provide more info about your actual use-case.
If you use gsub
with a regular expression that would work.
"hello, o".gsub /o$/, world
I believe that will do what you want.
EDIT
If you know that the word will always be surrounded with white space, beginning, or end of string you could use something like:
o = "whatever you want"
world = "the very long article you mentioned"
"an even longer article".gsub /^#{o}&|^#{o}\s|\s#{o}\s|\s#{o}&/, world
精彩评论