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

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(/\*$/, '')

Related

How to check if string include symbols?

How can I check if a string include symbol? It looks confusing to me:
class Beba
def initialize
while true
puts "Qfar emri deshironi ti vnoni bebes?"
##emri = gets.chomp.capitalize
if ##emri.scan(/\d+/).empty? && ##emri.scan(/\/./).empty?
puts "Ti e emertove beben me emrin: #{##emri}"
break
else
puts "Emri nuk mund te jete me numra/simbole, provoni perseri."
end
end
end
end
As you can see, at if##emri.scan(/\d+/).empty? && ##emri.scan(/\/./).empty?, I don't know what to do, like which method can I use for ##emri.scan(/\\.\).empty? to check if my string doesn't include any symbol?
For the specific characters you asked for, you can use this:
##emri.scan(/[!##$%^&*()_+{}\[\]:;'"\/\\?><.,]/).empty?
Will return true if no special character is found.
str !~ /[!##$%^&*()_+{}\[\]:;'"\/\\?><.,]/
returns true if and only if the string str contains none of the characters in the regex's character class (else false is returned).
Its seems you are looking for special characters.
Use something like
"Hel#lo".index( /[^[:alnum:]]/ )
It will return nil if no special charatcters.
[:alnum:] includes all 0-9, a-z, A-Z.
IF YOU WANT TO GO FOR SPECIFIC CHARATCERS
place all characters in a string & create regex like
characters = "!##$%^&*()_+{}[]:;'\"\/?><.,"
regex = /[#{characters.gsub(/./){|char| "\\#{char}"}}]/
& than use this regex to see if any of them exist in string like
if some_string =~ regex

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..."

Regex to check if string is just made up of special characters

I have some strings for which i have to check whether it is made up of all special characters in regex i tried something but its not working the way i want any help ?
str = "##%^"
regex = /[\?\<\>\'\,\?\[\]\}\{\=\-\)\(\*\&\^\%\$\#\`\~\{\}\#]/
str.match(regex)
You can do it with
/\A\W*\z/
The \W* matches any non-word character from the beginning (\A) till the end (\z) of string.
See demo:
class String
def onlySpecialChars?
!!self.match(/\A\W*\z/)
end
end
puts "##%^".onlySpecialChars? # true
puts "w##%^".onlySpecialChars? # false
If you have your own set of special characters, just use instead of \W. Just also note you have overescaped your regex, [?<>',?\[\]}{=)(*&^%$#`~{}#-] will suffice.

Check if a string is all-capitals in Rails

I'm looking to check if a string is all capitals in Rails.
How would I go about doing that?
I'm writing my own custom pluralize helper method and I would something be passing words like "WORD" and sometimes "Word" - I want to test if my word is all caps so I can return "WORDS" - with a capital "S" in the end if the word is plural (vs. "WORDs").
Thanks!
Do this:
str == str.upcase
E.g:
str = "DOG"
str == str.upcase # true
str = "cat"
str == str.upcase # false
Hence the code for your scenario will be:
# In the code below `upcase` is required after `str.pluralize` to transform
# DOGs to DOGS
str = str.pluralize.upcase if str == str.upcase
Thanks to regular expressions, it is very simple. Just use [[:upper:]] character class which allows all upper case letters, including but not limited to those present in ASCII-8.
Depending on what do you need exactly:
# allows upper case characters only
/\A[[:upper:]]*\Z/ =~ "YOURSTRING"
# additionally disallows empty strings
/\A[[:upper:]]+\Z/ =~ "YOURSTRING"
# also allows white spaces (multi-word strings)
/\A[[:upper:]\s]*\Z/ =~ "YOUR STRING"
# allows everything but lower case letters
/\A[^[:lower:]]*\Z/ =~ "YOUR 123_STRING!"
Ruby doc: http://www.ruby-doc.org/core-2.1.4/Regexp.html
Or this:
str =~ /^[A-Z]+$/
e.g.:
"DOG" =~ /^[A-Z]+$/ # 0
"cat" =~ /^[A-Z]+$/ # nil

Strip method for non-whitespace characters?

Is there a Ruby/Rails function that will strip a string of a certain user-defined character? For example if I wanted to strip my string of quotation marks "... text... "
http://api.rubyonrails.org/classes/ActiveSupport/Multibyte/Chars.html#M000942
I don't know if I'm reinventing the wheel here so if you find a built-in method that does the same, please let me know :-)
I added the following to config/initializers/string.rb , which add the trim, ltrim and rtrim methods to the String class.
# in config/initializers/string.rb
class String
def trim(str=nil)
return self.ltrim(str).rtrim(str)
end
def ltrim(str=nil)
if (!str)
return self.lstrip
else
escape = Regexp.escape(str)
end
return self.gsub(/^#{escape}+/, "")
end
def rtrim(str=nil)
if (!str)
return self.rstrip
else
escape = Regexp.escape(str)
end
return self.gsub(/#{escape}+$/, "")
end
end
and I use it like this:
"... hello ...".trim(".") => " hello "
and
"\"hello\"".trim("\"") => "hello"
I hope this helps :-)
You can use tr with the second argument as a blank string. For example:
%("... text... ").tr('"', '')
would remove all the double quotes.
Although if you are using this function to sanitize your input or output then it will probably not be effective at preventing SQL injection or Cross Site Scripting attacks. For HTML you are better off using the gem sanitize or the view helper function h.
I don't know of one out of the box, but this should do what you want:
class String
def strip_str(str)
gsub(/^#{str}|#{str}$/, '')
end
end
a = '"Hey, there are some extraneous quotes in this here "String"."'
puts a.strip_str('"') # -> Hey, there are some extraneous quotes in this here "String".
You could use String#gsub:
%("... text... ").gsub(/\A"+|"+\Z/,'')
class String
# Treats str as array of char
def stripc(str)
out = self.dup
while str.each_byte.any?{|c| c == out[0]}
out.slice! 0
end
while str.each_byte.any?{|c| c == out[-1]}
out.slice! -1
end
out
end
end
Chuck's answer needs some + signs if you want to remove all extra instances of his string pattern. And it doesn't work if you want to remove any of a set of characters that might appear in any order.
For instance, if we want a string to not end with any of the following: a, b, c, and our string is fooabacab, we need something stronger like the code I've supplied above.

Resources