10
10

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

ruby で変数をダイナミックに定義する例

Posted at

[Ruby] インスタンス変数、ローカル変数をメタに操作する

なにかのときに役立つかもしれない。
インスタンス変数、ローカル変数に 代入文を使わずに値を設定したり、列挙をする例です。

variable.rb
# coding: utf-8

range = (1..3)

puts '# =================================================='
puts '# 代入文をつかわずにインスタンス変数を設定する。'
puts '# =================================================='
puts "#---- before set ---"
instance_variables.each do |v|
  val = instance_variable_get "#{v}"
  puts "#{v} = #{val}"
end
puts

range.each do |idx|
  instance_variable_set "@v_#{idx}", idx * 10
end
puts "#---- after set ---"
instance_variables.each do |v|
  val = instance_variable_get "#{v}"
  puts "#{v} = #{val}"
end
puts

instance_variables.each do |v|
  remove_instance_variable(v)
end
puts "#---- after remove ---"
instance_variables.each do |v|
  val = instance_variable_get "#{v}"
  puts "#{v} = #{val}"
end
puts

puts "#----- before set local_val ---"
local_variables.each do |v|
  val = eval v.to_s
end
puts

local_1 = 0
local_2 = 0
local_3 = 0
puts '# =================================================='
puts '# 代入文を使わずにローカル変数に値を設定する。'
puts '# =================================================='
bd = binding
range.each do |idx|
  bd.local_variable_set "local_#{idx}".to_sym, idx * 100
end

puts "#----- show local variable  その1---"
puts "local_1 = #{local_1}"
puts "local_2 = #{local_2}"
puts "local_3 = #{local_3}"

puts "#----- show local variable その2---"
range.each do |idx|
  name = "local_#{idx}".to_sym
  val = bd.local_variable_get name
  puts "#{name} = #{val}"
end

puts "#----- show local variable その3 ---"
local_variables.each do |v|
  name = "#{v}".to_sym
  val = bd.local_variable_get name
  puts "#{name} = #{val}"
end

実行すると次のようになる。

stdout
$ ruby variable.rb
# ==================================================
# 代入文をつかわずにインスタンス変数を設定する。
# ==================================================
#---- before set ---

#---- after set ---
@v_1 = 10
@v_2 = 20
@v_3 = 30

#---- after remove ---

#----- before set local_val ---

# ==================================================
# 代入文を使わずにローカル変数に値を設定する。
# ==================================================
#----- show local variable  その1---
local_1 = 100
local_2 = 200
local_3 = 300
#----- show local variable その2---
local_1 = 100
local_2 = 200
local_3 = 300
#----- show local variable その3 ---
range = 1..3
local_1 = 100
local_2 = 200
local_3 = 300
bd = #<Binding:0x007fbe4b9e0870>

See

10
10
0

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
10
10

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?