Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 387
Kim Avatar asked Mar 21 '12 17:03

Kim


People also ask

How do you change the last character of a string in Ruby?

The chop method is used to remove the last character of a string in Ruby. If the string ends with \r\n , it will remove both the separators. If an empty string calls this method, then an empty string is returned. We can call the chop method on a string twice.

How do I remove the last character of a string?

The easiest way is to use the built-in substring() method of the String class. In order to remove the last character of a given String, we have to use two parameters: 0 as the starting index, and the index of the penultimate character.

How do you change the last element of a string?

replace() method to replace the last character in a string, e.g. const replaced = str. replace(/. $/, 'replacement'); . The replace method will return a new string with the last character replaced by the provided replacement.

What does \n do in Ruby?

In double quoted strings, you can write escape sequences and Ruby will output their translated meaning. A \n becomes a newline. In single quoted strings however, escape sequences are escaped and return their literal definition. A \n remains a \n .


1 Answers

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(/\*+$/, '') 
like image 65
pjumble Avatar answered Sep 25 '22 19:09

pjumble