Hashie::Mashã¯Rubygemsã®ããã±ã¼ã¸ã§å ¬éããã¦ããclassã®ã²ã¨ã¤ã§ï¼m.key = valueã®ãããªæ¸ãæ¹ã§keyã«ã¢ã¯ã»ã¹ã§ããHashã®ãããªãã®ï¼twitterããã±ã¼ã¸ã®å é¨ã§ã使ããã¦ããï¼
使ãæ¹
gemã³ãã³ãã§ã¤ã³ã¹ãã¼ã«ã§ããï¼
$ sudo gem install hashie
å©ç¨ããã«ã¯hashieãrequireããå¿ è¦ããã(Ruby1.8以åã®å ´åã¯å ã«require "rubygems"ãã¦ãã)ï¼
require "hashie"
以ä¸ï¼ã³ã¼ãä¾ï¼ããã ãã§ãªãã¨ãªãé°å²æ°ã¯åããã¨æãï¼
m = Hashie::Mash.new m.a = 1 m.b = "hoge" p m.a #=> 1 p m.b #=> "hoge"
Hashã§ã¯h[:key]ã®ããã«Hash#[]ã§è¦ç´ ã«ã¢ã¯ã»ã¹ããã®ã«å¯¾ãï¼Mashã§ã¯ã¡ã½ããå¼ã³åºãã®ãããªæ¸ãæ¹ã§è¦ç´ ã«ã¢ã¯ã»ã¹ã§ããï¼ããã¯method_missingãå®è£ ãããã¨ã§å®ç¾ããã¦ããï¼
Hashãªãã¸ã§ã¯ããHashie::Mashã«ãããã¨ãã§ããï¼ãã¹ãããHashã§ãOKï¼è¦ç´ ã«ã¢ã¯ã»ã¹ããããã®ã¡ã½ããåã¯keyãto_sãããã®ã«ãªãã®ã§ï¼to_sã®çµæãã¢ã¬ãªkeyããã¤Hashãå ¥ããã¨ã¢ã¬ãªãã¨ã«ãªãã®ã§æ³¨æï¼
m = Hashie::Mash.new({:foo => 1, "bar" => {:baz => 2}}) p m.foo #=> 1 p m.bar #=> <#Hashie::Mash baz=2> p m.bar.baz #=> 2
Hashã®ããã«Hashie::Mash#[]ã§ãè¦ç´ ã«ã¢ã¯ã»ã¹ã§ããï¼
m = Hashie::Mash.new({:foo => 1}) p m.foo #=> 1 p m[:foo] #=> 1 p m["foo"] #=> 1
eachãEnumerableã®ã¡ã½ããã使ããï¼
m = Hashie::Mash.new({:foo => 1, "bar" => {:baz => 2}}) m.each{|k, v| p [k, v]} #=> ["foo", 1] #=> ["bar", <#Hashie::Mash baz=2>]
twitterããã±ã¼ã¸ã§ã¯ï¼Twitter APIãè¿ããJSONãHashie::Mashã«å¤æãã¦ããã¡ã½ããã®æ»ãå¤ã¨ãã¦è¿ãããããã®ã«ä½¿ããã¦ãã(ã¯ã)ï¼
ãã¾ããããªãä¾
æ®å¿µãªããHashã§ã¯å¤§ä¸å¤«ã§ãHashie::Mashã ã¨ãã¾ããããªãå ´åãããï¼
to_sã®çµæãåãã«ãªãkeyãè¤æ°ããã¨ã©ã¡ããçæ¹ããã¢ã¯ã»ã¹ã§ããªããªãï¼
m = Hashie::Mash.new({"foo" => 1, :foo => 2}) p m.foo #=> 2 p m["foo"] #=> 2 p m[:foo] #=> 2
ãã¼ãIntegerã®å ´åã¯é常ã®ã¡ã½ããå¼ã³åºãã§ã¯è¦ç´ ã«ã¢ã¯ã»ã¹ã§ããªããªã©ã®åé¡ãããï¼
m = Hashie::Mash.new({1 => "one"}) p m.1 #=> SyntaxError: no .<digit> floating literal anymore; put 0 before dot p m[1] #=> "one" p m["1"] #=> "one" p m[:1] #=> SyntaxError: syntax error, unexpected tINTEGER, expecting tSTRING_CONTENT or tSTRING_DBEG or tSTRING_DVAR or tSTRING_END p m[:"1"] #=> "one"
循ç°åç §ãã¦ããHashã¯Hashie::Mashã«å¤æã§ããªãï¼
h = {} h[:a] = h p h #=> {:a=>{...}} m = Hashie::Mash.new(h) #=> SystemStackError: stack level too deep
以ä¸
æ軽ã«ä½¿ãããã§ã¯ãããã®ã®Rubygemsã®ããã±ã¼ã¸ãã¤ã³ã¹ãã¼ã«ããå¿ è¦ãããã®ã§ï¼å©ç¨ããå ´é¢ã¯ããèãã¦é¸ãã æ¹ãããããï¼
Hashie::Mashã®ã½ã¼ã¹ã¯GitHubで公開されているï¼çµæ§çãã®ã§method_missingãé¢ç½ã使ã£ãclassã®ä¾ã¨ãã¦èªãã§ã¿ãã®ã«ã¡ããã©ããããï¼