LoginSignup
6
6

More than 5 years have passed since last update.

ruby - attr_accessorで定義した属性とその値をto_sとかinspectで全部出したい

Posted at

属性名の配列をクラス変数に持って、それを使って属性と値を出力してるんだけど
クラス毎に同じようなことを毎回書くのもイヤな感じだし
なにかうまい方法はないかなあ

class Employee
  @@attrs = :id, :name, :birthday

  attr_accessor *@@attrs

  def inspect
    attrs = @@attrs.map{ |a| "#{a}=#{send(a)}" }.join(',')
    "#<#{self.class.name}:#{attrs}>"
  end
end
require 'date'

e = Employee.new
e.id = 123
e.name = 'hoge'
e.birthday = Date.new(1960, 12, 31)

p e # => #<Employee:id=123,name=hoge,birthday=1960-12-31>
6
6
4

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
6
6