What does << in Ruby mean?

Asked

Viewed 109 times

5

I’m studying a book of programming logic and wanted to know what it means << see what the book is applying to:

This balcony to maintain a help variable with the actual size used an array is very important and extremely used in several situations. We can remove our total_de_chutes variable and use the size :

limite_de_tentativas = 5

chutes = []

for tentativa in 1..limite_de_tentativas

chute = pede_um_numero chutes, tentativa,

limite_de_tentativas

chutes[chutes.size] = chute

if verifica_se_acertou numero_secreto, chute

break

end

end

But if Ruby has something to help us with the current size of a array, does it no longer have something that helps us to put a value at the end of it? Yes, we have seen the symbol << :

chutes = [100, 300, 500]

chutes << 600

puts chutes.size # imprime 4

puts chutes[3] # imprime 600

Therefore, our final code becomes even simpler:

da_boas_vindas

numero_secreto = sorteia_numero_secreto

limite_de_tentativas = 5

chutes = []

for tentativa in 1..limite_de_tentativas

chute = pede_um_numero chutes, tentativa,

limite_de_tentativas

chutes << chute

if verifica_se_acertou numero_secreto, chute

break

end

end

1 answer

3


This is the operador de concatenação. It can be used in data collection contexts. In the example shown it is adding a new item to a array.

He’s the same as writing array.concat(item) that does what is in the variable array have a new item.

Browser other questions tagged

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