Created
January 7, 2014 16:23
-
-
Save micodel/8301867 to your computer and use it in GitHub Desktop.
Print a right triangle: syntax question.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| =begin | |
| Hey, thanks for taking the time to help. | |
| I was under the impression that a defined method could see variables outside of the method. | |
| My original attempt to solve this problem was (example 1), where the variable star = "*" was defined outside the method. | |
| I understand that having a method variable defined in the method is more practical for reusing the method. | |
| But I was curious why it wouldnt work. | |
| The code worked as planned once the variable star was moved inside the method (example 2). | |
| =end | |
| # example 1 | |
| star = "*" | |
| def print_triangle(rows) | |
| rows.times do | |
| puts star | |
| star += "*" | |
| end | |
| end | |
| #example 2 | |
| def print_triangle(rows) | |
| star = "*" | |
| rows.times do | |
| puts star | |
| star += "*" | |
| end | |
| end |
Just to extrapolate a little further on what Allen put here:
Ruby has block scope, so when you define a variable without $ (global variables) or @ (instance variables) or @@ (class variables) or in all caps (constants) it can only be read for the block in which it falls under, in this case the method. Allen defined the @star instance variable in the global scope, so it can be read by any method that exists within that scope. When defining star as you did, it's only accessible in the global scope and not to the method print_triangle. In practice, example #2 of what you wrote is the best way to go. Here's a five minute quick read on scope: http://www.techotopia.com/index.php/Ruby_Variable_Scope.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
As I wrote my last definition I realize that socrates won't pass what I put down because it never calls that same method with a star parameter. Using splat(*) won't fix this problem either.
In "real life", I would always define star within the method like you have in example 2, UNLESS, you plan on using that same variable(star) multiple times which in case it would probably be all contained within a class and be an instance variable.
@star = "*"
def print_triangle(rows)
rows.times do
puts star
@star += "*"
end
end
This code will make your code pass, but the caveat here is that after running print_triangle, @star will also be changed forever to whatever that method makes it change to. So calling @star a second time will return the changed variable.