-2

I am trying to return a list/array of values from a range of (100..1000) that match the following criteria:

  1. 3 digit value
  2. All the digits in each value are unique.
$global_range = Array (100..999)
$fun = []

def listOfFunPossibilities
    # FUN values should meet the criteria below:
    # 1. 3 digit value
    # 2. All are unique

    $global_range.each do |i|
       if (!(/([0-9]).*?\1/)).match?(i)
           $fun.push(i)
       end
    end
    return $fun
end

listOfFunPossibilities()
Too Colline
  • 90
  • 1
  • 11

1 Answers1

2

You apply negation ! too early:

if (!(/([0-9]).*?\1/)).match?(i)

so you first negate a regex (that is true for some reason) and then you try to call match on true value

Use instead:

if !(/([0-9]).*?\1/.match?(i))

or even

if !/([0-9]).*?\1/.match?(i)
mrzasa
  • 22,895
  • 11
  • 56
  • 94
  • Nice suggestion, however, I get a new error ```no implicit conversion of Integer into String (TypeError)``` after I do that – Too Colline Oct 11 '19 at 08:57
  • Use `match?(i.to_s)`, because regex matching doesn't work on integers – mrzasa Oct 11 '19 at 09:00
  • Whoa. Why the heck is a `Regexp` falsy? That smells like a bug. – Jörg W Mittag Oct 11 '19 at 09:26
  • I was surprised as well. Try `puts 1 if /a/` and `puts 1 if !/a/` – mrzasa Oct 11 '19 at 09:27
  • I asked a question about it: https://stackoverflow.com/q/58340585/2988 Depending on the answers, I will file a bug. Interestingly, I was able to reproduce the behavior in at least three different implementations: YARV, JRuby, and TruffleRuby. MRuby doesn't have `Regexp`s, so the question doesn't come up. I'm trying to get Rubinius to build. – Jörg W Mittag Oct 11 '19 at 11:45
  • That's really interesting. Note that `!Regexp.new('')` is false so the regex created using a constructor is truthy. – mrzasa Oct 11 '19 at 11:47