Security is a major concern. Since eval will run any code passed to it, an attacker can enter code into your data file and take control of your program. It may not be important for small scripts for you, but in ruby โโon the rails server, security is important. Imagine we have the following code:
f=File.new("foobar.txt") f.puts Foo.new.tap {|foo| foo.bar="bork"}.inspect
This, assuming Foo not overwritten by inspect , will produce something like this:
#<Foo:0xff456a5 @bar="bork">
Obviously, this is an invalid Ruby syntax. Oddly enough, eval does not throw an error, but simply returns nil . This only makes this idea worse, since the variable you expected to be Foo is now just nil (the notorious error NoMethodError: undefined method 'bork' for nil:NilClass ).
Another big problem with this is security. Let's say your code saves the data to a file, say foo.txt and saves the inspect ed hash mapping bar to their respective baz es. Another program that needs to know these mappings for planning the FOO convention, and eval this file. Imagine that this file is located somewhere where a hacker can access it (which, when you think about it, almost anywhere). If these programs run on a RoR server, which also stores all the financial data of foo, a hacker can cause massive chaos. If this hacker entered the code in foo.txt , let's say, downloaded a malicious virus into the system and installed it, but still left the original hash code of the program at the end, it will be invisible. Even if you eval data with $SAFE=4 , the hacker can still damage the stability of the foo scheduling program, throwing errors, etc.
In general, although the inspect - eval approach works for base classes such as Hash , String , Array , etc., it depends on the class giving the exact syntactic representation itself. For most, if not all applications, it is a bad idea to use inspect - eval . YAML is preferred because it has a specific syntax for data, which means that executable code mixed with causes errors rather than thoughtlessly executed. In addition, many developers use inspect for debugging and will not expect the object to provide the dump file itself.
Other advantages of YAML are that it easily serializes complex objects. A tree of complex foos and bars would be easy to do with YAML, but using inspect would be a huge challenge. Ultimately, this can be seen as a JSON problem - executable code in the data being executed because eval used. inspect may be subtle for small utilities for itself, but it is never open to a large middle world in production code or code.