为什么 Ruby 中的方法内部不能有类? [英] Why cant there be classes inside methods in Ruby?

查看:30
本文介绍了为什么 Ruby 中的方法内部不能有类?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我可以在函数体内创建 Ruby 类吗?我似乎收到错误消息,告诉我这是不允许的,但我认为应该是因为类在这里太对象了.

<前>A级定义方法B级结尾结尾结束

此操作失败,并出现错误方法体中的类定义".如果不能,为什么不能在方法中创建类?

解决方案

class A定义方法self.class.const_set :B, Class.new {定义 foo'酒吧'结尾}结尾结尾一种新方法A::B.new.foo # =>'酒吧'

但是,为什么要在方法内部分配一个常量?这没有意义:常量是常量,你只能给它们赋值一次,这意味着你只能运行你的方法一次.那么,如果一个方法只运行一次,你为什么还要编写它呢?

Can I create Ruby classes within functions bodies ? I seem to be getting error which tells me its not allowed but I think it should be as classes are too objects here.

class A
    def method
        class B
        end
    end
end

This fails with error 'class definition inside method body. If we cant, why cant we create classes inside methods ?

解决方案

class A
  def method
    self.class.const_set :B, Class.new {
      def foo
        'bar'
      end
    }
  end
end

A.new.method
A::B.new.foo # => 'bar'

However, why do you want to assign a constant inside a method? That doesn't make sense: constants are constant, you can only assign to them once which means you can only run your method once. Then, why do you write a method at all, if it is only ever going to be run once, anyway?

这篇关于为什么 Ruby 中的方法内部不能有类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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