How do I parse out a string in rails? I have my form for submitting a height. Example: 5'9 I want the comma parsed and the 59 saved within the database
3 Answers
If you want to ignore anything other than numbers, use this regex
"5'9".gsub(/\D/, '')
# => "59"
"5 9".gsub(/\D/, '')
# => "59"
"5 feet 9 inches".gsub(/\D/, '')
# => "59"
'5" 9'.gsub(/\D/, '')
# => "59"
Regex Explanation: \D
stands for any character other than a digit.
There are a number of ways to do this. If you want to just remove the quote, you could use:
"5'9".gsub "'", ""
#=> "59"
or
"5'9".split("'").join("")
#=> "59"
If you want to save the 5 and the 9 in different attributes, you could try:
a = "5'9".split("'")
object.feet = a[0]
object.inches = a[1]
If you want to remove everything but the numbers you could use a regex:
"5'9".gsub /[^\d]/, ""
#=> "59"
If you have a different requirement, please update the question to add more detail.