ruby - Array of Strings to Convert to Mixed Array -



ruby - Array of Strings to Convert to Mixed Array -

i'm trying convert array of arrays consisting of ruby strings array of arrays consisting of strings , floats.

here attempt:

array = [["my", "2"], ["cute"], ["dog", "4"]] array.collect! |x| x.each |y| if y.gsub!(/\d+/){|s|s.to_f} end end end => [["my", "2.0"], ["cute"], ["dog", "4.0"]]

i'm looking rather homecoming [["my", 2.0], ["cute"], ["dog", 4.0]] did wrong?

what did wrong used gsub!. takes string , changes string. doesn't turn else, no matter (even if convert float in middle).

a simple way accomplish want is:

[["my", "2"], ["cute"], ["dog", "4"]].map{|s1, s2| [s1, *(s2.to_f if s2)]}

if not want create element array, replace contents, then:

[["my", "2"], ["cute"], ["dog", "4"]].each{|a| a[1] = a[1].to_f if a[1]}

if numerical strings appear in random positions, then:

[["my", "2"], ["cute"], ["dog", "4"]] .each{|a| a.each.with_index{|e, i| a[i] = a[i].to_f if a[i] , a[i] =~ /\d+/}}

ruby arrays string

Comments

Popular posts from this blog

web services - java.lang.NoClassDefFoundError: Could not initialize class net.sf.cglib.proxy.Enhancer -

Accessing MATLAB's unicode strings from C -

javascript - mongodb won't find my schema method in nested container -