文字列で返ってきたHashやArrayをそれぞれのクラスに再変換する'to_array'と'to_h'メソッド
APIやTCP socketsの返り値が強制的にstringになってしまう場合に、それを再び正しいクラスへ戻すメソッドです。
to_array
to_array gem
install 方法
gem install to_array
例
require 'to_array' array = ['foo', 'bar', 'hoge', 'fuga'] str = array.to_s p str # => "[\"foo\", \"bar\", \"hoge\", \"fuga\"]" p str.class # => String p str.size # => 30 re_converted = str.to_array p re_converted # => ["foo", "bar", "hoge", "fuga"] p re_converted.class # => Array p re_converted.size # => 4
to_h
str_to_hash gem
install 方法
gem install str_to_hash
例
require 'str_to_hash' hash = {'foo'=>'bar', 'hoge'=>'fuga'} str = hash.to_s p str # => "{\"foo\"=>\"bar\", \"hoge\"=>\"fuga\"}" p str.class # => String p str.size # => 30 re_converted = str.to_h p re_converted # => {"foo"=>"bar", "hoge"=>"fuga"} p re_converted.class # => Hash p re_converted.size # => 2
念のために・・・
一応既存のメソッドをoverwriteしちゃってないか確認
2.1.2 :001 > String.new.public_methods.include?(:to_array) => false 2.1.2 :002 > String.new.public_methods.include?(:to_h) => false 2.1.2 :003 > String.new.public_methods.size => 164 2.1.2 :004 > require 'str_to_hash' => true 2.1.2 :005 > require 'to_array' => true 2.1.2 :006 > String.new.public_methods.size => 166
OK!