Ruby 字符串#to_class
取自上一篇帖子,并进行了一些修改以响应sepp2k关于命名空间的评论,我已经实现了 String#to_class 方法。我在这里分享代码,我确实相信它可以以某种方式重构,特别是“i”计数器。感谢您的评论。
class String
def to_class
chain = self.split "::"
i=0
res = chain.inject(Module) do |ans,obj|
break if ans.nil?
i+=1
klass = ans.const_get(obj)
# Make sure the current obj is a valid class
# Or it's a module but not the last element,
# as the last element should be a class
klass.is_a?(Class) || (klass.is_a?(Module) and i != chain.length) ? klass : nil
end
rescue NameError
nil
end
end
#Tests that should be passed.
assert_equal(Fixnum,"Fixnum".to_class)
assert_equal(M::C,"M::C".to_class)
assert_nil "Math".to_class
assert_nil "Math::PI".to_class
assert_nil "Something".to_class
Taken from a previous post with some modifications to respond to sepp2k's comment about namespaces, I have implemented String#to_class method. I'm sharing the code here and I do believe that it could be refactored someway specially the "i" counter. Your comments are appreciated.
class String
def to_class
chain = self.split "::"
i=0
res = chain.inject(Module) do |ans,obj|
break if ans.nil?
i+=1
klass = ans.const_get(obj)
# Make sure the current obj is a valid class
# Or it's a module but not the last element,
# as the last element should be a class
klass.is_a?(Class) || (klass.is_a?(Module) and i != chain.length) ? klass : nil
end
rescue NameError
nil
end
end
#Tests that should be passed.
assert_equal(Fixnum,"Fixnum".to_class)
assert_equal(M::C,"M::C".to_class)
assert_nil "Math".to_class
assert_nil "Math::PI".to_class
assert_nil "Something".to_class
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
我会看一下
ActiveSupport::CoreExtensions::String::Inflections
特别是它的constantize
方法:I would take a look at
ActiveSupport::CoreExtensions::String::Inflections
specifically it'sconstantize
method:我出于好奇运行了一些基准测试,但我的解决方案非常慢!
这是一个带有基准的重构解决方案,希望有所帮助。
I ran some benchmarks by curiosity and my solution is very slow!
here is a refactored solution with benchmarks, hope that helps.
您可以使用递归:
You can use recursion: