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
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.
Comments
You want to look at the sub or gsub methods
height.gsub! "'", ''
Where sub replaces the first instance, and gsub replaces all instances and you could even do this on the model:
before_validation :remove_apostrophes # or before_save
protected
def remove_apostrophes
self.property.gsub! "'", ''
end