arraysrubyflatten

Ruby complex strings array to array of float


I'm trying to convert this (rather complex) string array of float strings into an array of float with no luck:

[  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 ]

What I have tried:

  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

Got me this:

[
  "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"
]

What I want to get:

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

Any clue?


Solution

  • To parse this string you can:

    onset.delete('[]').split.map(&:to_f)
    

    (1) Firstly delete brackets, (2) then split string to substrings by spaces and (3) finally convert to floats

    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]
    

    BTW Ruby has built-in method to get lines from the string, you don't need split it by new line character, just use string.lines