IliasP - 1 year ago 45

Ruby Question

I am trying to write a function that gives you the number of numbers need to complete a consecutive array. For example if we have the array [3,5,7] the function should return 2 (i.e. 4,6). I have come up with the code below but it gives me the following error? Any ideas why? Thanks!

`def consecutive(*arr)`

sorted = arr.sort

current_count = 0

sorted.each_index do |i|

next if i == sorted.length

difference = arr[i+1] - arr[i] - 1

current_count += difference

end

current_count

end

And this is the error:

`undefined method `-' for nil:NilClass`

(repl):9:in `block in Consecutive'

(repl):6:in `each_index'

(repl):6:in `Consecutive'

(repl):16:in `<main>'

Answer Source

If `arr`

is your array, you can do this:

```
arr = [3,1,5,7,8]
f,l = arr.minmax
#=> [1, 8]
l-f+1 - arr.size
#=> 3
```