0

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

1
  • 1
    Could you provide more info? Do you only ever want numbers saved into that field, or do you want to allow some punctation like periods?
    – Jay
    Commented Jul 22, 2014 at 15:25

3 Answers 3

1

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.

1

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.

0

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.