PJCHENder
PJCHENder

Reputation: 6010

Why I get NoMethodError by using to_yaml in Ruby

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

Upvotes: 1

Views: 527

Answers (1)

tadman
tadman

Reputation: 211610

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

require 'yaml'

Upvotes: 5

Related Questions