1

I have seen the question about "How do I print out the contents of an object in Rails for easy debugging?", and the answer showed that I can use to_yaml to print out the contents of Object. However, why I run the same code created by @jerhinesmith but get an NoMethodError?

class User
  attr_accessor :name, :age
end

user = User.new
user.name = "John Smith"
user.age = 30

puts user.inspect
#=> #<User:0x423270c @name="John Smith", @age=30>
puts user.to_yaml
#=> --- !ruby/object:User
#=> age: 30
#=> name: John Smith
main.rb:11:in <main>': undefined methodto_yaml' for #

@name="John Smith", @age=30> (NoMethodError) exited with non-zero status

Community
  • 1
  • 1
PJCHENder
  • 5,570
  • 3
  • 18
  • 35

1 Answers1

5

That method won't be defined until you load in the YAML library with:

require 'yaml'
tadman
  • 208,517
  • 23
  • 234
  • 262
  • Thanks for your replying, I am new hand of Ruby. I only know to require, but forget to add the quotation mark on 'yaml' – PJCHENder Feb 15 '17 at 03:07
  • The syntax is pretty forgiving, but it's still important. Hope that worked. If so, accept it as a solution when you can. Good luck! – tadman Feb 15 '17 at 04:00