TacoMaster6000
TacoMaster6000

Reputation: 324

Rails string parse for forms

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

Upvotes: 0

Views: 90

Answers (3)

Santhosh
Santhosh

Reputation: 29094

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.

Upvotes: 1

A Fader Darkly
A Fader Darkly

Reputation: 3626

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.

Upvotes: 1

ediblecode
ediblecode

Reputation: 11971

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

Upvotes: 0

Related Questions