Tbpgr Blog

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

書籍 Ruby Cookbook | メンバー変数の自動設定

パンくず

Ruby Cookbook
メンバー変数の自動設定

概要

メンバー変数の自動設定

内容

レシーバのインスタンス変数に値を設定
instance_variable_set

サンプルコード

# encoding: UTF-8
require "pp"

class Object
  private
  def set_instance_variables(binding, *variables)
    variables.each do |var|
      instance_variable_set("@#{var}", eval(var.to_s, binding))
    end
  end
end

class Hoge
  def initialize(hage=0, hoge=0, hige=0)
    set_instance_variables(binding, *local_variables)
  end
end

hoge = Hoge.new("hage", "hoge", "hige")
pp hoge

出力

#<Hoge:0x2b5b5c8 @hage="hage", @hige="hige", @hoge="hoge">