ç°¡åãªto_jsonã¢ã¸ã¥ã¼ã«ãæ¸ãã
ruby-jsonã§ã¯Objectã®to_jsonã¯ããªãã¸ã§ã¯ããto_sããæååã®JSON表ç¾ããè¿ãã®ã§ã以ä¸ã®ãããªã¢ã¸ã¥ã¼ã«ãæ¸ãã¦ã¿ã¾ãããã¤ã³ã¹ã¿ã³ã¹å¤æ°ãããã·ã¥ã®ããã«åºåãã¾ãã
module JsonSupport def to_json instance_variables.inject({}) { |h, name| h.store( name[1..-1], instance_variable_get(name)) h }.to_json end end
ãµã³ãã«ã¯ä»¥ä¸ã
require 'json/lexer' require 'json/objects' # ãã¹ãç¨ã¯ã©ã¹ã class Kitten include JsonSupport # JsonSupport ãinclude def initialize( name, age ) @name = name @age = age end end mii = Kitten.new( "mii", 1 ) puts mii.to_json
å®è¡çµæã§ãã
{"age":1, "name":"mii"}