Prev / Next

2010-03-29 / Hashie

Hash を拡張した
- Mash (Mocking Hash)
- Dash (Discrete Hash)
- Clash (Chainable Lazy Hash)
を扱うライブラリ.

ちょっとしたデータを扱うときに便利かも.


Mash

mash = Hashie::Mash.new
p mash.name?
mash.name = "foo"
p mash.name

mash = Hashie::Mash.new

# {author => {name => "bar"} } のようにしたい時は "!" を使う
mash.author!.name = "bar"

# 一度 "!" を使えば,次からは "!" なしで OK
mash.author.email = "[email protected]"

# {foo => {bar => {baz => "fuga"}}}
mash.foo!.bar!.baz = "fuga"




Dash

定義済みの property のみ操作できる.

require 'rubygems'
require 'hashie'

class Person < Hashie::Dash
  property :name
  property :email
  property :occupation, :default => "Rubyist"
end

# 定義した property には method としてアクセスできる
you = Person.new
p you.name
p you.occupation
p you.email
you.email = "[email protected]"
p you.email

# 定義していない property の追加はできない
begin
  you.fuga = "hoge"
rescue => e
  puts e
end

he = Person.new(:name => "fuga hoge")
p he.name
p he.occupation




Clash

複数の key, value を method chain で渡す.

c = Hashie::Clash.new

# method chain で要素を追加
# {:a => "a", :b => "b", :c => "c"}
c.a("a").b("b").c("c")

# {:z => {:b => "b", :c => "c"}}
c.z!.b("b").c("c")

# {:y => {:b => "b", :c => "c"}, :x => "x"}
# y! から _end! までが y の要素になる
c.y!.b("b").c("c")._end!.x("x")

p c


- intridea's hashie at master - GitHub
  http://github.com/intridea/hashie
- Intridea Blog: Hashie: The Hash Toolkit
  http://intridea.com/posts/hashie-the-hash-toolkit

comments powered by Disqus