Stefano Crocco
3/16/2008 2:14:00 PM
On Sunday 16 March 2008, Tom Cloyd wrote:
> Beginner woes, here, no doubt, but woes nevertheless.
>
> I'm exploring the wonders of the Object class, and I see Object#to_yaml.
> Seems pretty obvious what to expect here, which would seem to account
> for the total lack of documentation in each of the gazillion instances
> of this method which appear in core library. Still, let's test it...
>
> irb(main):010:0> [2,5,3,6,'abc'].to_yaml
> NoMethodError: undefined method `to_yaml' for [2, 5, 3, 6, "abc"]:Array
> from (irb):10
> from :0
>
> Can someone explain what just happened?
>
> Thanks!
>
> t.
Yes. to_yaml is defined in the yaml.rb file, so you need to require it before
using to_yaml:
irb(main):001:0> require 'yaml'
=> true
irb(main):002:0> [2,3,4,5, 'abc'].to_yaml
=> "--- \n- 2\n- 3\n- 4\n- 5\n- abc\n"
How are you supposed to know that to_yaml is not in ruby core but in the
standard library? I don't really know. When I started using ruby some years
ago, I downloaded a version of the rdoc documentation from
www.ruby-doc.org which only included documentation for the core classes (that
is, those you can use without need to require some files), while documentation
for the standard library was in a separate package. Unfortunately, the
documentation you can find nowadays includes both core and standard library.
This has the very unpleasant side effect of displaying together methods which
come from the core classes and methods which come from files in the standard
library (which should be required before using such methods). At any rate, at
the top of the page, just below the name of the class, there's a list of the
files which have been used to generate the documentation for the class. If a
method listed in the documentation doesn't seem to exist, try requiring those
files. In the specific case of Object#to_yaml, this doesn't work, though,
since the file where the method is defined, lib/yaml/rubytypes.rb, can't be
required directly, but only requiring 'yaml'. It can give you a hint.
Stefano