加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

Ruby – 如何使用method参数作为变量的名称?

发布时间:2020-12-17 01:22:55 所属栏目:百科 来源:网络整理
导读:我如何使用参数值作为对象的实例变量名? 这是对象 Class MyClass def initialize(ex,ey) @myvar = ex @myothervar = ey endend 我有以下方法 def test(element) instanceofMyClass.element #this obviously doesnt workend 如何让test方法返回myvar或myothe
我如何使用参数值作为对象的实例变量名?

这是对象

Class MyClass    
    def initialize(ex,ey)
      @myvar = ex
      @myothervar = ey
    end
end

我有以下方法

def test(element)
  instanceofMyClass.element  #this obviously doesnt work
end

如何让test方法返回myvar或myothervar值,具体取决于element参数.我不想写if条件,但是如果可能的话,我想通过元素将myvar或myother var传递给对象实例.

解决方法

def test(element)
  instanceofMyClass.send(element.to_sym)  
end

如果instanceofMyClass没有响应元素,则会丢失方法错误.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读