Skip to content

Instantly share code, notes, and snippets.

@barnes7td
Last active December 16, 2015 16:39
Show Gist options
  • Save barnes7td/5464694 to your computer and use it in GitHub Desktop.
Save barnes7td/5464694 to your computer and use it in GitHub Desktop.
Print Grid Solutions
# This is a conglomeration of solution possibilites, collected and put together by Ryan Matthews - reposted here by Timothy
def print_grid(x=5,y=5)
size = 4
0.upto(size) do |a|
0.upto(size) do |b|
if b == x && a == y
print "X"
else
print "0"
end
end
puts ""
end
nil
end
# Next! This will be an excercise for you to walk through. You might find it helpful to try each line individually in irb.
def print_grid(x=5,y=5)
matrix = Array.new(5) { Array.new(5,0) }
matrix[y][x] = "X" if matrix[y] && matrix[y][x]
matrix.each { |r| puts r.join }
nil
end
# The most complex part here is the first line. We are creating a new Array, telling it we want 5 elements, and we pass a block. That block will set the value for each element in the array. In this case we are creating a new array with 5 elements, each of which is a 0.
def print_grid(x=nil,y=nil)
grid = Array.new(5) {"O" * 5}
grid[x][y] = "X" if x && y
puts grid
end
# This is a mix of the previous two code examples. Much cleaner! Refactoring is fun.
# This is just showing off. Getting the method down to 2 lines.
require 'matrix'
def print_grid(x=nil, y=nil)
m = Matrix.build(5,5) { |r,c| (r==y && c==x)? "X" : "0" }
m.to_a.map {|i| puts i.join}
end
# The most important thing to understand here is the turnary. That is the if/else statement on the first line.
#
# ```ruby
# >> (true) ? "hi" : "bye"
# => "hi"
# >> (false) ? "hi" : "bye"
# => "bye"
# ```
#
# You don't need to understand the Matrix stuff. If you want to look into it, go for it.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment