#!/usr/bin/env ruby
# -*- coding: utf-8 -*-
class Hoge
# setterは公開されていない
attr_reader :fuga
def initialize
@fuga = 'fuga'
# getter/setter共に公開されていない
@hige = 'hige'
end
end
hoge = Hoge.new
p hoge.fuga
# => "fuga"
# インスタンス変数の名前を文字列で指定して
# 外から強制的に書き換える
name = "@fuga"
hoge.instance_variable_set(name, 'fugafuga') if hoge.instance_variable_defined?(name)
p hoge.fuga
# => "fugafuga"
# シンボルでも指定できる
hoge.instance_variable_set(:@fuga, 'fugafugafuga') if hoge.instance_variable_defined?(:@fuga)
p hoge.fuga
# => "fugafugafuga"
# 読むのも当然できる
p hoge.instance_variable_get('@hige') if hoge.instance_variable_defined?('@hige')
# => "hige"
More than 5 years have passed since last update.
Register as a new user and use Qiita more conveniently
- You get articles that match your needs
- You can efficiently read back useful information
- You can use dark theme