Home > Enterprise >  Filling an array with contents
Filling an array with contents

Time:08-28

Write a function that produces an array with the numbers 0 to N-1 in it.

I wrote:

def arr(n)
   Array.new(n) { |n| n =1 }
end

It gives me the following result

Test Results: Fixed tests should pass fixed tests Expected: [0, 1, 2, 3], instead got: [1, 2, 3, 4]

How do I change it to include "0"?

CodePudding user response:

What about creating an array from a Range object

def arr(n)
  (0...n).to_a
end

Or if you want solve it using Array.new, you can go like this:

def arr(n)
  Array.new(n) { |n| n }
end

(just don't add 1 to n inside a block)

CodePudding user response:

You can use splat-operator and range with ... that exclude end of range

def arr(n)
  [*0...n]
end
arr(4)
# => [0, 1, 2, 3]

CodePudding user response:

it can be achieved by using

for 0 to n-1

def arr(n)
   arr = (0...n).to_a
end

for 0 to n

def arr(n)
   arr = (0..n).to_a
end
  • Related