如何为动态实例变量设置attr_accessor? [英] How do I set an attr_accessor for a dynamic instance variable?

查看:120
本文介绍了如何为动态实例变量设置attr_accessor?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在类中动态创建了一个实例变量:

I dynamically created an instance variable within my class:

class Mine
  attr_accessor :some_var

  def intialize
    @some_var = true
  end

  def my_number num
    self.instance_variable_set "@my_#{num}", num
  end
end

我现在如何将@my_#{num}设置为attr值?

How do I make @my_#{num} now as an attr value?

例如我希望能够做到这一点:

e.g. I want to be able to do this:

dude = Mine.new
dude.my_number 1
dude.my_1
=> 1

推荐答案

此答案不会污染类空间,例如..如果我执行mine.my_number 4,则Mine的其他实例将不会获得方法..之所以发生这种情况,是因为我们使用对象的单例类而不是该类.

this answer doesn't pollutes the class space, example.. if i do mine.my_number 4 then the other instances of Mine will not get the my_4 method.. this happens because we use the singleton class of the object instead of the class.

class Mine
  def my_number num
    singleton_class.class_eval { attr_accessor "my_#{num}" }
    send("my_#{num}=", num)
  end
end

a = Mine.new
b = Mine.new
a.my_number 10 #=> 10
a.my_10 #=> 10
b.my_10 #=> NoMethodError

这篇关于如何为动态实例变量设置attr_accessor?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆