-
-
Save TravisL12/6175381 to your computer and use it in GitHub Desktop.
| # Andrews' CODE | |
| def times_table(rows) # <-- defines method and how many rows passed as argument | |
| 1.upto(rows) do |x| # <-- You start first loop with value x | |
| line = "" | |
| 1.upto(rows) do |y| # <-- begin 2nd (nested) loop with value y | |
| line += "#{x*y}\t" # <-- x=1 therefore 1*1, 1*2, 1*3. When done x=2 2*1, 2*2, 2*3.... (x=3, 3*1, 3*2, 3*3...) | |
| end | |
| puts line | |
| end # <-- incremement to the next x value | |
| end | |
| # The basics are, that you will increment an 'x' value and then run the entire 'y' loop. | |
| # Then you increase 'x' and then run the whole 'y' loop again. | |
| # An alternative looping system could be written without the 'line' variable: | |
| 1.upto(rows) do |x| | |
| 1.upto(rows) do |y| | |
| print "#{ x * y }\t" | |
| end | |
| puts | |
| end | |
| # Take note of why the 'puts' is placed after the 'y' loop. | |
| # That's to give a line break after each row of values has been printed. |
Your code is doing a little more than it needs to but I completely see where you're coming from, let's try to clear this up.
Try these examples in irb:
puts "Travis"; puts "Andrew"
print "Travis"; print "Andrew"
What you should notice in the output is that:
'puts' will print a value to screen and include a line break => "Travis" line break "Andrew"
'print' will print a value to screen with no line break at the end => "TravisAndrew"
Moving on...
When you add to the 'line' variable (string object) with the '+=' operator it concatenates (combines) the words. So what your 'y' loop is doing is adding x*y\t to the 'line' variable over and over again until the 'y' loop terminates. At the end of the 'y' loop you 'puts' that final 'line' variable which prints the row of numbers and puts a line break. Then x increments and it starts all over again.
What I did instead is just 'print' each value and after my 'y' loop I have an empty 'puts' that simply gives me a line break for my next row of numbers. Our approaches are virtually the same, but I just eliminated the need for the 'line' variable because we really don't need it.
Interesting. Your way is definitely better. Thanks for clearing that up. My line spacing was redundant with the \t.
Thanks for going through this. The part that got me stuck is I thought the purpose of line 4 of my code when I had the extra space was to provide a space between the output numbers. Since it's not like that, what is its purpose? I guess my trouble is more related to the ruby syntax and understanding the nuances between print and puts. For example, why does using print in your code eliminate the need for the whole "line" string?