Last active
August 29, 2015 14:24
-
-
Save iwan/2b53fe348d81748d4d54 to your computer and use it in GitHub Desktop.
Convert a string numeric array to numeri array
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
module StringToArrayConverter | |
NUMERIC_ARRAY_REGEX = /^\[([\d,\s\.\-\+]+)\]$/ | |
def to_numeric_array | |
m = NUMERIC_ARRAY_REGEX.match(self.strip) | |
m[1].split(",").map{|e| e.include?(".") ? e.to_f : e.to_i} | |
end | |
def is_a_numeric_array? | |
!NUMERIC_ARRAY_REGEX.match(self.strip).nil? | |
end | |
end | |
class String | |
include StringToArrayConverter | |
end | |
# Use: | |
"[1, 2.345, 3 ,-5,+3,0.0] ".to_numeric_array # => [1, 2.345, 3, -5, 3, 0.0] | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment