Forum: Ruby YAML on 1.8.3 question

Announcement (2017-05-07): is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see and for other Rails- und Ruby-related community platforms.
george.moschovitis (Guest)
on 2005-11-16 13:54
(Received via mailing list)
Hello all,

I have a yaml file that I parse like this

yaml = YAML.parse(yaml_str)

the 'yaml_str' variable holds the serialized version of an Object.
Lets say this object hase 2 attributes, 'title' and 'body'.

How can I access them from the 'yaml' variable. Ie I want an imaginary
method 'lookup':

yaml.lookup['title'] # => returns the title value.

I used to do this with a little hack in 1.8.2, this hack does not work
on 1.8.3, I am looking for a portable way to do this.

thanks in advance for any help,

mfp (Guest)
on 2005-11-16 14:39
(Received via mailing list)
On Wed, Nov 16, 2005 at 08:53:08PM +0900, George M. wrote:
> method 'lookup':
> yaml.lookup['title'] # => returns the title value.

require 'yaml'
o =
o.instance_eval{ @title = "foo"; @body = "bar" }
s = YAML.dump(o) # => "!ruby/object \nbody: bar\ntitle: foo\n"

# for instance
def add_lookup(obj)
  def obj.lookup(x); instance_variable_get "@#{x}" end

o2 = YAML.load(s)
o2.lookup "title" # => "foo"
o2.lookup "body" # => "bar"
[RUBY_VERSION, RUBY_RELEASE_DATE] # => ["1.8.3", "2005-09-24"]
george.moschovitis (Guest)
on 2005-11-16 14:45
(Received via mailing list)

I forgot to tell you that the original object does not exist in the
current context.

so, o = YAML.load does not yield an object.

george.moschovitis (Guest)
on 2005-11-16 14:51
(Received via mailing list)

just show that:

obj = YAML.load(str)

does the trick

GGarramuno (Guest)
on 2005-11-16 20:57
(Received via mailing list)
George M. ha escrito:

> method 'lookup':
> yaml.lookup['title'] # => returns the title value.

Huh?  You missed the point.
YAML just serializes your object, so if your object supports a method
called title, loading it back in should too.  If your object is a hash,
then you can use a hash syntax.  Example:

> irb
irb>class A
irb> attr_accessor :x
irb>  def initialize
irb> @x = 2
irb>  end
irb>a =
irb>require 'yaml'
irb>b = YAML.load( YAML.dump(a) )
george.moschovitis (Guest)
on 2005-11-17 13:36
(Received via mailing list)
> Huh?  You missed the point.

Probably you missed the point ;-) Read the later emails that explain
my question in more detail...

This topic is locked and can not be replied to.