2
1

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で呼び出された変数名を取得する

2
Last updated at Posted at 2017-12-03
できなかった = Class.new do
  def method_missing(method)
    top_variales = eval('instance_variables', TOPLEVEL_BINDING)
    called_variable = top_variales.each do |v|
      variable = eval(v.to_s, TOPLEVEL_BINDING)
      break v if self == variable
    end
    puts "#{called_variable}#{method}ことはできなかった"
  end
end

@悪魔 = できなかった.new
@悪魔.倒す # => @悪魔を倒すことはできなかった
@悪魔.叩く # => @悪魔を叩くことはできなかった

Kernel#eval

は文字型を評価できます

array = [10, 20]
element = 30
eval('array << element') # => [10, 20, 30]

num = 10
eval('numbers'.delete('bers')) # => 10

Kernel#binding

スコープをオブジェクトにまとめたものです。Kernel#evalの第二引数に渡せばそこで評価されます。
また、Rubyには事前に定義された定数TOPLEVEL_BINDINGが用意されており、トップレベルのスコープのBindingになっています。

class MyClass
  def my_method
    @x = 1
    binding
  end
end

b = MyClass.new.my_method

eval '@x', b # => 1

obj.instance_variables

定義済みのインスタンス変数の一覧をハッシュになって配列で返します

@a = 1
@b = 2
instance_variables # => [:@a, :@b]
2
1
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
2
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?