LoginSignup
29
29

More than 5 years have passed since last update.

Ruby 文字列をハッシュに変換

Last updated at Posted at 2015-03-30

"x: 100, y: 200, z: 300" のような文字列を
{x: 100, y: 200, z: 300 }のようなハッシュ{sym: int}に変換する方法
ruby2.2で探してみたところ、それ用のメソッドが無いようなので書いてみた。

補足

2.1以降 Array#to_h
それ以前 Hash[ ]

パターン1 一旦配列にする

文字列を":"と","区切りで二次元配列にして、それを二個ずつ取り出してハッシュに変換する。

def to_hash(str)
  array = str.delete(' ').split(/[:,]/)
  array.each_slice(2).map {|k, v| [k.to_sym, v.to_i] }.to_h 
end

パターン2 eval使う(要注意)

超簡単、ruby怖い。

def to_hash(str)
  eval("{#{str}}")
end

パターン3 scanで正規表現を使う (追記)

@jnchitoさんより。

def to_hash(str)
  str.scan(/(\w+):\s+(\d+)/).map{|k, v| [k.to_sym, v.to_i] }.to_h
end

速度比較

上記の2つをそれぞれ1000回実行した平均(小数点2桁目以降は誤差みたいなものなので省略)
※パターン3を追記

  • "x: 100, y: 200, z: 300"
パターン1  4.2e-06
パターン2  4.8e-06
パターン3  3.6e-06
  • "x: 100, y: 200, z: 300, a: 1000, b: 20"
パターン1  5.7e-06
パターン2  5.7e-06
パターン3  4.8e-06
  • "x: 100, y: 200, z: 300, a: 1000, b: 20, c: 800"
パターン1  6.4e-06
パターン2  6.3e-06
パターン3  5.6e-06

追記したパターン3が最も速い結果になった。
要素が増えるにつれパターン3と他との差が開いていく。

もっと良い方法があったりしたらおねがいします!

29
29
3

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
29
29