def get_each_const(const, context=::Object) const.to_s.split(/::/).inject(context) {|parent, c| parent.const_get(c) } end module Foo module Bar module Hoge module Fuga end end end end bar = get_each_const "Foo::Bar" # -> Foo::Bar fuga = get_each_const "Hoge::Fuga", bar # -> Foo::Bar::Hoge::Fuga
よくあるやつ。 "ruby inject 定数" でググるとほぼ同じコードがどっさり見つかるというアレ。
よくあるやつだし、よくつかうんだけど、コアにないので書かざるをえない。せっかくなので context を受け取って、それの配下から探すようにした。
そういや、なんで Module#const_get なんだろう…。 Module#get_const じゃだめな理由ってあるのかなあ。