Created
July 16, 2011 04:23
-
-
Save tetu1225/1086001 to your computer and use it in GitHub Desktop.
RubyでHashを構造体にしてアクセサのように取得する
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def Struct(hash) | |
# ハッシュのキーを構造体のメンバーとして設定 | |
st = Struct.new(*hash.keys) | |
# 構造体に新しい要素を突っ込む | |
st.new( | |
*hash.values.map do |s| | |
# ハッシュの場合は再帰 | |
Hash === s ? Struct(s) : s | |
end | |
) | |
end | |
obj = Struct(:a => {:b => {:c => { :d => [:foo, :bar, :baz] }}}) | |
p obj.a.b.c.d[0] #=> :foo | |
p obj.a.b.c.d #=> [:foo, :bar, :baz] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment