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

ruby-on-rails – Ruby – 在循环中创建具有动态名称的方法

发布时间:2020-12-17 01:35:04 所属栏目:百科 来源:网络整理
导读:也许这不是明智的问题……但我有一个问题. 我正在玩 Ruby并尝试在循环中创建带有动态名称的方法,如下所示: class Test ..... class methods ..... for i in 1..100 def method_#{i} my_hash[:test].first[i] end endend 我注意到这是不可能的,所以…是否有
也许这不是明智的问题……但我有一个问题.
我正在玩 Ruby并尝试在循环中创建带有动态名称的方法,如下所示:

class Test

    .....
    class methods 
    .....

    for i in 1..100
       def method_#{i}
          my_hash[:test].first[i]
       end
    end
end

我注意到这是不可能的,所以…是否有任何解决方案使用:define_method,或:发送来解决我的问题,并得到如下方法:
method_0,method_1,method_2等返回my_hash [:test] .first [1],my_hash [:test] .first [2]等?

解决方法

您可以使用define_method来完成.这是代码:

class Test
    .....
    class methods 
    .....

    1.upto(100) do |num|
        define_method("method_#{num}") do
            my_hash[:test].first[num]
        end
    end
end

(编辑:李大同)

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

    推荐文章
      热点阅读