简体   繁体   中英

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 method to_yaml' for #

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

在您使用以下方法加载到YAML库中之前,将不会定义该方法:

require 'yaml'

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM