对Ruby字符串进行分类 [英] Classify a Ruby string

查看:84
本文介绍了对Ruby字符串进行分类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个程序可以创建类似于以下内容的类:

I have a program that create classes which looks like:

  MyClass = Class.new do
    def initialize; end
    # ...
  end

但是我想从字符串动态命名MyClass.而且因为它是一个类的名称,所以我想对该字符串进行分类(例如,感谢Rails方法):

But I would like to name dynamically MyClass, from a string. And because it's for the name of a class, I would like to classify that string, for instance (thanks Rails methods):

  "hello_world".classify # => "HelloWorld"

我不知道在纯Ruby中是否有用于此的方法.

I don't know if in pure Ruby there is a method for that.

谢谢

推荐答案

不确定您的问题是只构造驼峰字符串,还是为其分配新创建的类.因为对于后者,您应该使用Module::const_set方法:

Not sure if your question is only about constructing a camelcased string, or also about assigning a newly created class to it. Because, for the latter, you should use Module::const_set method:

class_name = 'MyClass'
#=> "MyClass"
klass = Class.new do
  def foo
    "foo"
  end
end
#=> #<Class:0xa093a68>
Object.const_set class_name, klass
#=> Module::MyClass
MyClass.new.foo
#=> "foo"

这篇关于对Ruby字符串进行分类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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