check if it has a comma and delete a comma if it is in the string by Ruby

1

Hi, how do I delete a string to check if the last variable's string word is a comma, and how do I delete that comma at the end of the string type variable?

test="my name is neymar,"

Then leave test="my name is neymar"

In Ruby code I need

    
asked by anonymous 19.04.2018 / 14:58

3 answers

1

Use the String # sub method that replaces the first occurrence of a string or pattern:

"meu nome é neymar,".sub(/,\z/, '')
 => "meu nome é neymar"
"substitui so a , do final,".sub(/,\z/, '')
 => "substitui so a , do final"

\z is the default for the end of the string, then /,\z/ is the default for a comma followed by the end of the string. .sub(/,\z/, '') , so it replaces a comma at the end of the string with "nothing" - that is, it removes the comma at the end of the line, but not the commas in other parts of the text.     

25.04.2018 / 21:01
0

You can use the String#delete method.

'Essa é uma string de testes, ok?'.delete(',')
=> 'Essa é uma string de testes ok?'

The cool thing about this method is that you can write some expressions. Supposing I want to remove anything other than numbers from a string:

'+55 41 9 9182-8217'.delete('^0-9')
=> "5541991828217"
    
21.04.2018 / 13:36
0

Hello, basically I would do so

def remove_last_character(text, character)
  string_to_array = text.split("")
  string_to_array.pop if string_to_array.last == character
  string_to_array.join("")
end

remove_last_character("meu nome, é neymar,", ",")

Result:

2.5.0 :026 > remove_last_character("meu nome, é neymar,", ",")
 => "meu nome, é neymar"
    
24.04.2018 / 17:06