Rails string parse for forms - ruby-on-rails

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

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.

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

Related

Ruby: trim or replace leading digits

I have a string in the following form:
'123string89continues...'
What is the most elegant way to replace or trim the leading digits? Note, there can be more or less than 3 digits, but at least one will always be present.
'1string89continues...' # This can happen
'0123456789string89continues...' # This can happen
'string89continues...' # This cannot happen
'123string89continues...'[/\D.*/]
#⇒ "string89continues..."
Try this one
"123asdads".sub(/A\d+/, "")
=> "asdads"
"1asdads".sub(/A\d+/, "")
=> "asdads"
"asdads".sub(/A\d+/, "")
=> "asdads"
You can use slice! to delete a specific portion from a string:
string = '123string89continues...'
string.slice!(/\A\d+/) #=> "123"
string #=> "string89continues..."

Truncate sentences in rails?

I've got a helper that I'm using to truncate strings in Rails, and it works great when I truncate sentences that end in periods. How should I modify the code to also truncate sentences when they end in question marks or exclamation points?
def smart_truncate(s, opts = {})
opts = {:words => 12}.merge(opts)
if opts[:sentences]
return s.split(/\.(\s|$)+/).reject{ |s| s.strip.empty? }[0, opts[:sentences]].map{|s| s.strip}.join('. ') + '...'
end
a = s.split(/\s/) # or /[ ]+/ to only split on spaces
n = opts[:words]
a[0...n].join(' ') + (a.size > n ? '... (more)' : '')
end
Thanks!!!
You have the truncate method
'Once upon a time in a world far far away'.truncate(27, separator: /\s/, ommission: "....")
which will return "Once upon a time in a..."
And if you need to truncate by number of words instead then use the newly introduced truncate_words (since Rails 4.2.2)
'And they found that many people were sleeping better.'.truncate_words(5, omission: '... (continued)')
which returns
"And they found that many... (continued)"

How to remove "$" and "," from a price field in Rails

I am saving a price string to my database in a decimal-type column.
The price comes in like this "$ 123.99" which is fine because I wrote a bit of code to remove the "$ ".
However, I forgot that the price may include a comma, so "$ 1,234.99" breaks my code. How can I also remove the comma?
This is my code to remove dollar sign and space:
def price=(price_str)
write_attribute(:price, price_str.sub("$ ", ""))
# possible code to remove comma also?
end
You can get there two ways easily.
String's delete method is good for removing all occurrences of the target strings:
'$ 1.23'.delete('$ ,') # => "1.23"
'$ 123,456.00'.delete('$ ,') # => "123456.00"
Or, use String's tr method:
'$ 1.23'.tr('$, ', '') # => "1.23"
'$ 123,456.00'.tr('$ ,', '') # => "123456.00"
tr takes a string of characters to search for, and a string of characters used to replace them. Consider it a chain of gsub methods, one for each character.
BUT WAIT! THERE'S MORE! If the replacement string is empty, all characters in the search string will be removed.

ruby on rails, replace last character if it is a * sign

I have a string and I need to check whether the last character of that string is *, and if it is, I need to remove it.
if stringvariable.include? "*"
newstring = stringvariable.gsub(/[*]/, '')
end
The above does not search if the '*' symbol is the LAST character of the string.
How do i check if the last character is '*'?
Thanks for any suggestion
Use the $ anchor to only match the end of line:
"sample*".gsub(/\*$/, '')
If there's the possibility of there being more than one * on the end of the string (and you want to replace them all) use:
"sample**".gsub(/\*+$/, '')
You can also use chomp (see it on API Dock), which removes the trailing record separator character(s) by default, but can also take an argument, and then it will remove the end of the string only if it matches the specified character(s).
"hello".chomp #=> "hello"
"hello\n".chomp #=> "hello"
"hello\r\n".chomp #=> "hello"
"hello\n\r".chomp #=> "hello\n"
"hello\r".chomp #=> "hello"
"hello \n there".chomp #=> "hello \n there"
"hello".chomp("llo") #=> "he"
"hello*".chomp("*") #=> "hello"
String has an end_with? method
stringvariable.chop! if stringvariable.end_with? '*'
You can do the following which will remove the offending character, if present. Otherwise it will do nothing:
your_string.sub(/\*$/, '')
If you want to remove more than one occurrence of the character, you can do:
your_string.sub(/\*+$/, '')
Of course, if you want to modify the string in-place, use sub! instead of sub
Cheers,
Aaron
You can either use a regex or just splice the string:
if string_variable[-1] == '*'
new_string = string_variable.gsub(/[\*]/, '') # note the escaped *
end
That only works in Ruby 1.9.x...
Otherwise you'll need to use a regex:
if string_variable =~ /\*$/
new_string = string_variable.gsub(/[\*]/, '') # note the escaped *
end
But you don't even need the if:
new_string = string_variable.gsub(/\*$/, '')

How do I create spaces between every four integers in Ruby?

I am trying to take the following number:
423523420987
And convert it to this:
4235 2342 0987
It doesn't necessarily have to be an integer either. In fact, I would prefer it to be a string.
You can use String::gsub with a regular expression:
=> 'abcdefghijkl'.gsub(/.{4}(?=.)/, '\0 ')
'abcd efgh ijkl'
class String
def in_groups_of(n, sep=' ')
chars.each_slice(n).map(&:join).join(sep)
end
end
423523420987.to_s.in_groups_of(4) # => '4235 2342 0987'
423523420987.to_s.in_groups_of(5, '-') # => '42352-34209-87'
To expand on #Mark Byer's answer and #glenn mcdonald's comment, what do you want to do if the length of your string/number is not a multiple of 4?
'1234567890'.gsub(/.{4}(?=.)/, '\0 ')
# => "1234 5678 90"
'1234567890'.reverse.gsub(/.{4}(?=.)/, '\0 ').reverse
# => "12 3456 7890"
If you are looking for padded zeros in case you have less than 12 or more than 12 numbers this will help you out:
irb(main):002:0> 423523420987.to_s.scan(/\d{4}/).join(' ')
=> "4235 2342 0987"
irb(main):008:0> ('%d' % 423523420987).scan(/\d{4}/).join(' ')
=> "4235 2342 0987"
Loop through each digit and if the loop index mod 4 = 0 then place a space.
Modulus in Ruby

Resources