How was ". include?" developed in Ruby?

Asked

Viewed 102 times

3

I was trying to check if a letter is included in an array without using the .include? but I can’t get the same result. Anyone has any idea how .include? from "inside"?

The code in question is a kind of hangman game. The player kicks a letter, the letter is included in a array which is shown at each kick in order to inform the kicks made. If the player kicks a letter that has already been kicked, the game must inform that the kick has already been made and ask for a new kick.Has a loop while that repeats the request for kicks while the player does not miss 5 times.

chutes_ate_agora = ["a","b","c","d"] #chutes hipotéticos
novo_chute = gets.strip

for chute in chutes_ate_agora
    if chute == novo_chute
       puts "já chutou letra #{novo_chute}"
       next  #vai para o loop while para pedir um novo chute
    else
       chutes_ate_agora << novo_chute
    end
end

1 answer

3


Has the his source code. As I could see is as obvious as possible, it runs through the whole array with a loop and filters whether each element is the same as the one you are looking for. Once you find the first one you can close.

VALUE
rb_ary_includes(VALUE ary, VALUE item)
{
    long i;
    VALUE e;

    for (i=0; i<RARRAY_LEN(ary); i++) {
    e = RARRAY_AREF(ary, i);
    if (rb_equal(e, item)) {
        return Qtrue;
    }
    }
    return Qfalse;
}

With editing the correct code would be this:

def includes(array, valor)
    for item in array
        if item == valor
           return true
        end
    end
    return false
end

chutes_ate_agora = ["a","b","c","d"]
novo_chute = gets.strip
teste = includes(chutes_ate_agora, novo_chute)
if teste then
   puts "já chutou letra #{novo_chute}"
else
   chutes_ate_agora << novo_chute
end
print chutes_ate_agora

See working on ideone. And in the repl it.. Also put on the Github for future reference.

Of course it only has disadvantages to do so. Use what you have ready.

  • To inform the specific problem, I can put the code here by comment or edit the question?

  • Edit the question if no one else answers before.

  • edition made, sorry if it has not been in the most appropriate way, I am new here.

  • And what is the goal? It seems to me that everything is ok.

  • The problem is that when I enter with a kick that has already been done, it warns that it has already been done, but still stores the repeated kick in the array of kicks, which should only happen if it was a shot that was not done.

  • Do you have any reason not to use the include?

  • Just to see if I can get the same result without this "facilitator".

  • Anyway, the question has been answered, thank you very much!!

  • You get the same thing if you do it right. I posted it, but it doesn’t make sense.

Show 4 more comments

Browser other questions tagged

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