 ajmalafif
10/4/2012 - 8:09 PM

## [Bloc - ruby weekly] Print a 5 x 5 grid

[Bloc - ruby weekly] Print a 5 x 5 grid

``````# Define a method and accept an unspecified number of arguments and insert them into an
# array called coords. The array is created with the "*".
def print_grid_1a(*coords)
# Create an array called grid consisting of 5 elements each with a string
# consisting of 5 O's
grid = Array.new(5) {"O" * 5}
# Assign the variable x to the first element of the coords array and y to the second
x, y = coords
# Change the O to an X in the x indexed character inside the string ("OOOOO")
# that is in the y element of the grid array
grid[y][x] = "X" if x
# Print each element of the grid with a newline after each element
puts grid
end

#Error Checking
def print_grid_1b(*coords)
grid = Array.new(5) {"O" * 5}
# Extra error checking = If the max of the first two elements of the coords array
# (converted to an integer, in case of nil) is less than 5
x, y = coords if coords[0..1].max.to_i < 5
grid[y][x] = "X" if x
puts grid
end

######################################################

def print_grid_2a(*coords)
# Create a empty array called grid
grid = []
# 5 times insert a string consisting of 5 O's into the grid array
5.times {grid << "O" * 5}
x, y = coords
grid[y][x] = "X" if x
puts grid
end

#Error Checking
def print_grid_2b(*coords)
grid = []
5.times {grid << "O" * 5}
x, y = coords
# Extra error checking = If x is not nil and x is less than 5 and y is less than 5
grid[y][x] = "X" if x && x < 5 && y < 5
puts grid
end``````