AltBrian - 3 months ago 8

Ruby Question

I'm trying to write a function that receives a value,

`val`

This is the code that I have written so far:

`def next_numb(n)`

x = n + 3

if x % 2 == 1 && x % 3 == 0

return x

end

end

How can I test for unique numbers? Also, if I enter 12 the answer is 15 and the same is for 13.

Answer

To test if the number only has unique values, you can do this:

```
num.to_s.split('').uniq == num.to_s.split('')
```

You are splitting each number into its individual digits, as strings, and then running `uniq`

to remove duplicates, and, if that is the same as the array without `uniq`

, then you have a number with non-duplicate digits.

If you add this to your `if`

statement, it will get pretty long, so I suggest you wrap this in a method that returns `true`

or `false`

:

```
def unique_digits?(num)
num.to_s.split('').uniq == num.to_s.split('')
end
```

Your `if`

statement will be:

```
def next_numb(n)
x = n + 3
if x % 2 == 1 && x % 3 == 0 && unique_digits?(x)
return x
end
end
```

I noticed something else about your code, it will only add 3 to `n`

and checks if the number meets all of the conditions, if so, it will return the number, and if not, it will return `nil`

.

If you have an input of `15`

, your function will return `nil`

, because `18`

is not odd. The right number to return is `21`

, so you will need a loop:

```
def next_numb(n)
x = n + 1
until x % 2 == 1 && x % 3 == 0 && unique_digits?(x)
x += 1
end
x
end
def unique_digits?(num)
num.to_s.split('').uniq == num.to_s.split('')
end
next_numb(13) #=> 15
next_numb(15) #=> 21
next_numb(125) #=> 129
```