Ad
  • Custom User Avatar

    Thanks for the explanation. really helps.

  • 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

    This comment is hidden because it contains spoiler information about the solution

  • 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.