0

I have an object like this

class Place
  def initialize(x,y)
    @x = x
    @y = y
  end
end

So, I have to emulate a dynamic grid with size X,Y. For example 3x5 (width, height).

I need to save all the "Place" objects in the array, with all the possible values, Place(1,1), Place(1,2), Place(1,3)... Place(3,5).

I tried this way (inside Grid)

def createPlaces width, height
    @places = Array.new(width * height)

    (0..width).to_a.each do |x|
      (0..height).to_a.each do |y|
        @places.push(Place.new(x,y))
      end
    end
  end

But is not working. How can I do it?

2
  • One Ruby convention is to use snake-case for names of variables and methods. You don't have to conform, but 99%+ of Rubiests do. Commented Sep 16, 2017 at 19:35
  • You might mean 0...width, where that is equivalent to 0..width-1. Width 10 would mean 11 entries in your array with your code, which is wrong. Commented Sep 16, 2017 at 21:10

2 Answers 2

3
@places = (0...width).to_a.product((0...height).to_a).map do |x, y|
  Place.new(x,y)
end

Thanks @tadman, there are to be triple-dotted ranges to exclude the tight borders from ranges ([0, width)). That makes an amount of elements exactly equal width and height.

Sign up to request clarification or add additional context in comments.

1 Comment

.. vs ... here as well.
1

Change

@places = Array.new(width * height)

to

@places = Array.new

Array#push creates a new element at the end of array, since you already created an array with certain number of elements, and then pushing more elements into it - you may be observing first width * height elements to be nil

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.