Skip to content

Instantly share code, notes, and snippets.

@tetu1225
Created July 16, 2011 04:23
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tetu1225/1086001 to your computer and use it in GitHub Desktop.
Save tetu1225/1086001 to your computer and use it in GitHub Desktop.
RubyでHashを構造体にしてアクセサのように取得する
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