简体   繁体   中英

Ruby string escaping, for serialization (string dumping and loading)

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 in 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:

  1. Replace a parameter (for example " world ") in a text by a value (for example " o ").
  2. 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM