14

I'm trying to use y object in Rails 3.2.6/Ruby 1.9.3 console to get nicely formatted yaml output for an ActiveRecord object, but for some reason it isn't working for me. I've used it in the past, but somewhere along the way it broke. I get the following output when I try:

NameError: undefined local variable or method `yaml' for main:Object
approxiblue
  • 6,982
  • 16
  • 51
  • 59
swrobel
  • 4,053
  • 2
  • 33
  • 42

2 Answers2

36

The y method is actually an extension to the Kernel object put in place by the Syck YAML parser/emitter. Here are the last few lines of lib/ruby/1.9.1/syck.rb:

module Kernel
    def y( object, *objects )
        objects.unshift object
        puts( if objects.length == 1
                  YAML.dump( *objects )
              else
                  YAML.dump_stream( *objects )
              end )
    end
    private :y
end

By default, Ruby 1.9.3 uses the Psych parser/emitter instead of Syck (I can only presume they're pronounced differently), and Psych doesn't declare such a method.

If you really loved y, you can simply use Syck instead of Psych in the console:

Loading development environment (Rails 3.2.5)
1.9.3p194 :001 > y 'hello'
NoMethodError: undefined method 'y' for main:Object
1.9.3p194 :002 > YAML::ENGINE.yamler = 'syck'
"syck"
1.9.3p194 :003 > y 'hello'
--- hello
nil

I'll also use this chance to plug awesome_print, which does for basically everything what y does for YAML.

Brandan
  • 14,735
  • 3
  • 56
  • 71
  • 4
    Love awesome_print! Thanks for the rec! – swrobel Aug 01 '12 at 06:06
  • 1
    if you put that line (YAML::ENGINE.yamler = 'syck') in your ~/.irbc then the 'y' method will always be available to you when you go to load irb or rails console – concept47 Jul 19 '13 at 05:47
8

For rails 4/ruby 2 you could use just

puts object.to_yaml
eKek0
  • 23,005
  • 25
  • 91
  • 119
  • This is what I've been doing. But then I came across what I thought my be a shorthand using y object. I guess I was wrong :( – user12121234 Oct 16 '15 at 18:17