Ruby ã® sprintf ã§ååä»ããã©ã¡ã¼ã¿
å
æ¥ä¼ç¤¾ã®å¾è¼©ã«æãã¦è²°ã£ããã§ãããRuby 1.9 ãã Kernel.#sprintf ã String#% ã Hash ãåãåããããã«ãªã£ã¦ãããã§ããã
ãã£ã¨ç¥ããªãã£ããã§ããã便å©ã ã¨æã£ãã®ã§è©¦ãã¦ã¿ã¾ããã
ããã«ãããæåå㧠SQL ã§ã®ååä»ããã¬ã¼ã¹ãã«ãã¿ãããªäºãç°¡åã«ã§ããããã«ãªãã¾ãã
ruby 1.9.3p194 ã«ã¦ç¢ºèªãã¾ããã
åã«å¤ãåãè¾¼ãã ãã§ãæ¡æ°ãªã©ã®æ¸å¼ãæå®ããªãå ´å㯠%{} ã§å²ãã§ååãä»ãã¾ãã
hash = {name: 'akishin', price: 9999} sprintf "%{name} æ§ã®ãæ¯æãéé¡ã¯ %{price} åã«ãªãã¾ãã", hash #=> "akishin æ§ã®ãæ¯æãéé¡ã¯ 9999 åã«ãªãã¾ãã" # Kernel.#format format "%{name} æ§ã®ãæ¯æãéé¡ã¯ %{price} åã«ãªãã¾ãã", hash #=> "akishin æ§ã®ãæ¯æãéé¡ã¯ 9999 åã«ãªãã¾ãã" # String#% "%{name} æ§ã®ãæ¯æãéé¡ã¯ %{price} åã«ãªãã¾ãã" % hash #=> "akishin æ§ã®ãæ¯æãéé¡ã¯ 9999 åã«ãªãã¾ãã" # ååã§æå®ããå ´åã¯åããã©ã¡ã¼ã¿ãè¤æ°ååºåã§ãã > sprintf "%{lang} %{lang} %{lang}", lang: :Ruby #=> "Ruby Ruby Ruby"
æ¸å¼ãæå®ããå ´å㯠%<> ã®æ¹ã使ç¨ãã¾ãã
# æ¡æ°ãªã©ã®æ¸å¼ãæå®ããå ´å㯠%<> ã使ã sprintf "%{year}å¹´%<month>02dæ%<day>02dæ¥", year: 2012, month: 9, day: 1 #=> "2012å¹´09æ01æ¥"
æååã®ãã³ãã¬ã¼ããç¨æãã¦ããã¦å¼æ°ãåãè¾¼ããããªå¦çã¯çµæ§å¤ãã¨æãã®ã§ãå¤ããããæ¸ããããã«ãªã£ã¦å¬ããã§ãã
ä»å¾ã¯ç©æ¥µçã«ä½¿ã£ã¦è¡ãããã¨æãã¾ãã
åè
sprintfããå¼æ°ã«Hashãåã£ã¦ããã¼ã§åç
§ã§ããããã«ãªã£ã
http://d.hatena.ne.jp/xibbar/20081001#1222833103
ç¥ã£ã¦å¾ãã21ã®Rubyã®ããªãã¢ãªè¨æ³
http://melborne.github.com/2011/06/22/21-Ruby-21-Trivia-Notations-you-should-know-in-Ruby/
module function Kernel.#format
http://rurema.clear-code.com/1.9.3/method/Kernel/m/format.html
instance method String#%
http://rurema.clear-code.com/1.9.3/method/String/i/=25.html