Tbpgr Blog

Employee Experience Engineer tbpgr(てぃーびー) のブログ

ActiveSupport | Object#instance_values/instance_variable_names

概要

Object#instance_values/instance_variable_names

詳細

Object#instance_values/instance_variable_namesについて

Object#instance_values/instance_variable_names

instance_values:インスタンス変数の値をハッシュで取得する。
instance_variable_names:インスタンス変数名文字列配列で取得する。
詳しくはサンプルを参照

サンプル

# encoding: utf-8
require "active_support/core_ext/object/instance_variables"
require 'attributes_initializable'
require 'tbpgr_utils'

class Hoge
  include AttributesInitializable
  attr_accessor_init :hoge, :hige, :hage
end

Hoge.new do |h|
  h.hoge = "hoge"
  h.hige = "hige"
  h.hage = "hage"
  puts_eval "h.instance_values", binding
  puts_eval "h.instance_variable_names", binding
end

__END__
下記はTbpgrUtils gemの機能
puts_eval
AttributesInitializable
attr_accessor_init

https://rubygems.org/gems/tbpgr_utils
https://github.com/tbpgr/tbpgr_utils

出力

h.instance_values # => {"hoge"=>"hoge", "hige"=>"hige", "hage"=>"hage"}
h.instance_variable_names # => ["@hoge", "@hige", "@hage"]