如何获取对象的所有属性,包括那些为零的属性?

How to get all attributes of an object including those which are nil?

我需要获取对象的所有属性。我知道有一个方法 attributes,但它没有 return 属性为 nil。 例如:

class User
  include Mongoid::Document

  field :name
  field :email
  field :age
end

u = User.new(email: 'foo@bar.com', name: 'foo')
u.save
u.attributes # {'email' => 'foo@bar.com', 'name' => 'foo'}

我需要 u.attributes 到 return {'email' => 'foo@bar.com', 'name' => 'foo' 'age' => nil}

有一种方法 as_json 可以满足我的要求,但速度要慢得多。速度很重要。

我找到了一个快速的解决方案

self.attribute_names.map { |name| [name, self[name]] }.to_h

它满足了我的所有需求 =)