【发布时间】:2010-11-29 17:43:45
【问题描述】:
取自 previous 的帖子,经过一些修改以回应 sepp2k 关于命名空间的评论,我已经实现了 String#to_class 方法。我在这里分享代码,我相信它可以以某种方式特别是“i”计数器进行重构。感谢您的 cmets。
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
【问题讨论】:
标签: ruby metaprogramming introspection