Importing from YAML

T

Toby Rodwell

I've learned that a very quick and easy way to save a Ruby object to a
file is to use YAML e.g.

def saveMyObject
File.open(self.fileName,"a+") { |f|
f.write(self.to_yaml)
f.close
}
end

However, the article which showed this did not then explain how this
process could be reversed. I assume there must be a an equivalent
simple use of file 'read', but a straight forward 'read' seems to give
just a string, and I can find no 'from_yaml' method whihc would read
YAML-formatted text straight into a Ruby object (and thus re-create that
object originally used to create the YAML file) . I'm sure there must
be a quick and easy way to do this - any suggestions?

Thanks in advance.
 
J

James Edward Gray II

Jordan Callicoat wrote:
...

Many thanks Jordan. For anyone interested I've just given it a go and
the reverse of the above code seems to be quite simply

def LoadMyObject
myObject = YAML.load_file(self.fileName)
end

No need to assign to a local variable there, since it goes out of
scope as soon as you leave the method on the next line.

James Edward Gray II
 
J

James Edward Gray II

Oops, that should be 'loadMyObject' of course ...

Actually, the Ruby convention is to methods and variables like_this
and classes and modules LikeThis.

James Edward Gray II
 
E

Eero Saynatkari

Toby said:
I've learned that a very quick and easy way to save a Ruby object to a
file is to use YAML e.g.

def saveMyObject
File.open(self.fileName,"a+") { |f|
f.write(self.to_yaml)
f.close
}
end

No-one mentioned it but the f.close in the File.open block
is not required--the whole idea behind the block is to use
it to close the file automatically after it has executed.
 

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

Similar Threads

YAML troubles 5
puzzled by yaml error .. 0
Deep YAML 5
YAML & readlines & modify text files 15
Understanding YAML and this practice in general 11
YAML and NArray 1
Ruby exceptions and YAML 2
Yaml append and query 0

Members online

Forum statistics

Threads
473,790
Messages
2,569,637
Members
45,348
Latest member
RoscoeNevi

Latest Threads

Top