脳汁portal

アメリカ在住(だった)新米エンジニアがその日学んだIT知識を書き綴るブログ

文字列で返ってきたHashやArrayをそれぞれのクラスに再変換する'to_array'と'to_h'メソッド

APITCP socketsの返り値が強制的にstringになってしまう場合に、それを再び正しいクラスへ戻すメソッドです。

to_array

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

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!