-1

I know I could use eval to get the string back like below:

"".inspect  == "\"\"" # true
eval("\"\"") == ""    # true

But besides eval, is there an another way to do it?

xdazz
  • 158,678
  • 38
  • 247
  • 274
  • 3
    What are you really trying to do? Why do you need to do this? It doesn't make much sense. – the Tin Man Jun 24 '13 at 02:07
  • `String::class_eval{"\"\""}` might do what you want. –  Jun 24 '13 at 02:09
  • @theTinMan What I want to do is get `""` from string `"\"\""`, for example. I have some data which is the result of string's inspect result, I need to revert them back to the orignal string. – xdazz Jun 24 '13 at 02:10
  • `#inspect` in your case merely puts double quotes around the escaped string, just like `#dump`. – Boris Stitnicky Jun 24 '13 at 02:11
  • possible duplicate of [What's the best way to escape and unescape strings?](http://stackoverflow.com/questions/8639642/whats-the-best-way-to-escape-and-unescape-strings) – Darshan Rivka Whittle Jun 24 '13 at 02:30
  • Yes, we know you want to recover a string created by inspect, but that's not how data should be transferred or serialized, so if you are receiving strings like that, there is a code-smell in the air. That's something that might need to be addressed. – the Tin Man Jun 24 '13 at 03:28

2 Answers2

2

In your case, "" is an empty string. "\"\"" is something completely else: A string that, when it is fed to something, yields your "" empty string. And that something, in this case, is Ruby interpreter. In other words, "\"\"" dump is specifically intended to be eveluated by Ruby interpreter, wheter in eval, instance_eval, class_eval, or ruby command line, or irb, or what...

Even if there is another way to do it, that way will only end up emulating Ruby interpreter. So I dare to say, no, it does not make too much sense to do it another way.

Boris Stitnicky
  • 12,444
  • 5
  • 57
  • 74
1

But besides eval, is there an another way to do it?

Yes possible,look below using YAML :

require 'yaml'

YAML.load("\"\"") # => ""
YAML.load("\"\"") == "" # => true
Arup Rakshit
  • 116,827
  • 30
  • 260
  • 317