Skip to content

Instantly share code, notes, and snippets.

@iwan
Last active August 29, 2015 14:24
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save iwan/2b53fe348d81748d4d54 to your computer and use it in GitHub Desktop.
Save iwan/2b53fe348d81748d4d54 to your computer and use it in GitHub Desktop.
Convert a string numeric array to numeri array
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