Techioz Blog

Rubyの複雑な文字列配列からfloatの配列へ

概要

この(かなり複雑な)float文字列の文字列配列をfloatの配列に変換しようとしていますが、うまくいきません。

[  5.85142857   6.10684807   6.15328798   6.31582766   6.96598639
   7.61614512   7.87156463   8.73070295   9.38086168   9.65950113
  10.51863946  12.07437642  12.32979592  13.39791383  13.63011338
  13.86231293  14.09451247  14.72145125  14.97687075  15.85922902 ]

私が試したこと:

  def onset_string_to_array(onset)
    # Remove the brackets.
    onset = onset.tr('[]', '')
    # Strip whitespace.
    onset = onset.strip
    # Split by newline character.
    onset_lines = onset.split("\n")
    # loop through each line.
    onset_array = []
    onset_array.push *onset_lines.map do |line|
      # Split by space character.
      line_array = line.split
      # Return one float per line.
      line_array.map(&:to_f)
    end
    onset_array
  end

これをもらいました:

[
  "0.53405896   0.7662585    0.99845805   1.20743764   1.41641723",
  "   1.64861678   1.85759637   2.32199546   3.43655329   3.57587302",
  "   4.08671202   4.7600907    4.99229025   5.87464853   6.52480726",
  "   6.78022676   7.66258503   8.33596372   9.4737415   10.12390023",
  "  10.35609977  10.750839    11.2152381   11.88861678  12.14403628",
  "  12.60843537  12.84063492  13.04961451  13.69977324  13.95519274",
  "  14.11773243  14.58213152  14.79111111  15.4644898   15.69668934",
  "  16.60226757  17.27564626  17.5078458   18.39020408  19.06358277",
  ## More lines...
  " 126.54875283 127.45433107 129.03328798 129.21904762 130.77478458",
  " 131.00698413 131.86612245 132.81814059 133.35219955 134.55963719",
  " 135.14013605"
]

取得したいもの:

[ 0.53405896, 0.7662585, 0.99845805, 1.20743764, 1.41641723, 1.64861678, ...]

どんな手掛かり?

解決策

この文字列を解析するには、次のことができます。

onset.delete('[]').split.map(&:to_f)
  1. まず括弧を削除し、(2) 次に文字列をスペースで部分文字列に分割し、(3) 最後に浮動小数点数に変換します。
onset =
  '[  5.85142857   6.10684807   6.15328798   6.31582766   6.96598639
      7.61614512   7.87156463   8.73070295   9.38086168   9.65950113
     10.51863946  12.07437642  12.32979592  13.39791383  13.63011338
     13.86231293  14.09451247  14.72145125  14.97687075  15.85922902 ]'

onset.delete('[]').split.map(&:to_f)
# => 
# [5.85142857,
#  6.10684807,
#  6.15328798,
#  6.31582766,
#  6.96598639,
#  7.61614512,
#  7.87156463,
#  8.73070295,
#  9.38086168,
#  9.65950113,
#  10.51863946,
#  12.07437642,
#  12.32979592,
#  13.39791383,
#  13.63011338,
#  13.86231293,
#  14.09451247,
#  14.72145125,
#  14.97687075,
#  15.85922902]

ところで、Rubyには文字列から行を取得する組み込みメソッドがあり、改行文字で分割する必要はなく、string.linesを使用するだけです。