Ad
  • Custom User Avatar

    Thanks for the explanation. really helps.

  • Custom User Avatar

    genuinely, how is this more efficient than some of the others?

    To me it looks less readable which, and efficient code can tends to be less readable, but that doesn't apply the other way round.

    is it the modulo operations being more efficient than the 'even?' method, for example?

  • Custom User Avatar

    @njohnson7

    I tried it in irb, and found:

    let arr == ["0"], then /#{arr}{2}/ == /["0"]{2}/.

    I think /["0]{2}/ and /[0"]{2}/ work the same as /["0"]{2}/.

  • Custom User Avatar

    very clever. thanks for explaining! I just realised why I was slightly confused and that's because I misunderstood the kata in the 1st place. still managed to pass the case tests though haha

  • Custom User Avatar

    Ok, I'll walk through it piece by piece.

    Let's assume num1 is 11122233 and num2 is 1223.

    The first part converts num1 to a string and calls the scan method to scan for triple digits.

    The Regexp to find triple digits /(.)\1\1/ matches a single character (.) followed by two identical characters.
    The \1 is a back-reference and means match what was matched earlier by the first capture group.

    So, given the input 11122233, the scan will find the two triples 111 & 222 and return the Array [["1"], ["2"]]

    Next, the any? method is used on the resulting Array. any? returns true if the block returns a truthy value (anything that's not false or nil) for any element of the Array.
    In this case, we're saying "do any of the numbers found as triples in num1 also exist as doubles in num2?"

    The Regexp used in this block /#{n}{2}/ means match what's in the variable n exactly two times.

    So, here's what happens for each element of the Array [["1"], ["2"]]:

    /#{n}{2}/ === num2.to_s
       /1{2}/ === 1223.to_s
       /1{2}/ === "1223"
     => false
    
    
    /#{n}{2}/ === num2.to_s
       /2{2}/ === 1223.to_s
       /2{2}/ === "1223"
     => true
    

    There is a double 2 in 1223 so the any? returns true.

    By the way, the statement /pattern/ === variable is a way to match a Regexp against a String and just get a boolean result. It's not strictly necessary in this case, it's more of a personal habit of mine.

    Finally the ternary operator is used to convert the boolean result from any? to a 0 or 1.

    The statement foo ? bar : baz is equivalent to:

    if foo
      bar
    else
      baz
    end
    

    I hope that explains everything, apologies if I'm stating the obvious for any of the concepts being used here.

  • Custom User Avatar

    can someone explain this please?