2018-10-12 16:35:31 -04:00
|
|
|
---
|
|
|
|
|
title: Ruby String Operations
|
2019-08-16 15:39:34 -03:00
|
|
|
localeTitle: Operações com String Ruby
|
2018-10-12 16:35:31 -04:00
|
|
|
---
|
|
|
|
|
Tanto a concatenação quanto a multiplicação podem ser executadas em strings.
|
|
|
|
|
|
|
|
|
|
## Concatenação:
|
|
|
|
|
|
2019-08-16 15:39:34 -03:00
|
|
|
* Strings podem ser unidas usando qualquer um dos seguintes métodos:
|
2018-10-12 16:35:31 -04:00
|
|
|
|
|
|
|
|
* `+` operador
|
|
|
|
|
* `<<` operador
|
|
|
|
|
* método `.concat`
|
|
|
|
|
|
|
|
|
|
```ruby
|
2019-08-16 15:39:34 -03:00
|
|
|
"Hello" + " World" + "!"
|
|
|
|
|
#=> Hello World!
|
|
|
|
|
|
|
|
|
|
"Hello" << " World!"
|
|
|
|
|
#=> Hello World!
|
|
|
|
|
|
2018-10-12 16:35:31 -04:00
|
|
|
string1 = "Hello"
|
2019-08-16 15:39:34 -03:00
|
|
|
string2 = " World!"
|
|
|
|
|
string1.concat(string2)
|
|
|
|
|
#=> Hello World!
|
2018-10-12 16:35:31 -04:00
|
|
|
```
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
## Multiplicação:
|
|
|
|
|
|
2019-08-16 15:39:34 -03:00
|
|
|
* As strings podem ser multiplicadas por um valor inteiro usando o operador `*`.
|
|
|
|
|
```ruby
|
|
|
|
|
"Hello" * 3
|
|
|
|
|
#=> HelloHelloHello`
|
|
|
|
|
```
|
2018-10-12 16:35:31 -04:00
|
|
|
|
2019-08-16 15:39:34 -03:00
|
|
|
## Substituindo uma substring:
|
2018-10-12 16:35:31 -04:00
|
|
|
|
2019-08-16 15:39:34 -03:00
|
|
|
* Podemos procurar por sub-strings ou usar o Regex para pesquisar e substituir caracteres em uma string.
|
|
|
|
|
```ruby
|
|
|
|
|
"Hey mom, look at this string".sub('mom', 'dad')
|
|
|
|
|
#=> Hey dad, look at this string
|
|
|
|
|
```
|
2018-10-12 16:35:31 -04:00
|
|
|
|
|
|
|
|
## Comparação:
|
|
|
|
|
|
2019-08-16 15:39:34 -03:00
|
|
|
* Strings podem ser comparadas, retornam `-1`, `0`, `+1` ou `nil` dependendo se string é _menor que_, _igual a_ ou _maior que_ outra string.
|
2018-10-12 16:35:31 -04:00
|
|
|
|
|
|
|
|
```ruby
|
2019-08-16 15:39:34 -03:00
|
|
|
"abcdef" <=> "abcde"
|
|
|
|
|
#=> 1
|
|
|
|
|
"abcdef" <=> "abcdef"
|
|
|
|
|
#=> 0
|
|
|
|
|
"abcdef" <=> "abcdefg"
|
|
|
|
|
#=> -1
|
|
|
|
|
"abcdef" <=> "ABCDEF"
|
|
|
|
|
#=> 1
|
2019-08-16 15:15:03 -03:00
|
|
|
```
|