check if you have a comma and delete a comma if you have it in the string by Ruby

Asked

Viewed 169 times

1

hi how do I delete to check if the last word of the variable with string is comma and if this is how do I delete this comma at the end of the variable string type

test = "my name is Neymar,"

then leave test = "my name is Neymar"

In Ruby code I need

3 answers

1

Use the method String#sub which 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, so /,\z/ is the default for a comma followed by the end of the string. .sub(/,\z/, ''), so replace a comma at the end of the string with "nothing" - that is, remove the comma at the end of the line, but not the commas that are in other parts of the text.

  • 2

    Enter comments. Explain WHY this code answers the question and what is the return of it. What the sub() is doing with the data?

0

Hello, basically I would do like this

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,", ",")

Upshot:

2.5.0 :026 > remove_last_character("meu nome, é neymar,", ",")
 => "meu nome, é neymar"

0

You can use the method String#delete.

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

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

'+55 41 9 9182-8217'.delete('^0-9')
=> "5541991828217"

Browser other questions tagged

You are not signed in. Login or sign up in order to post.