Last active
December 19, 2015 10:29
-
-
Save keccers/5940591 to your computer and use it in GitHub Desktop.
Learning Ruby --> Instance Variable Anomaly ---> Learn from my mistakes!
This file contains 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
#A PROBLEM OF SCOPE, LEARN FROM MY ERROR | |
#ORIGINAL: This doesn't work! Ruby's getting confused. Even though I've called readers/accessors on my instance variables, | |
#within the methods Ruby thinks that "budget" and "day of shooting" are actually local variables--otherwise, you couldn't have a | |
#local variable and an instance variable with the same name. More here: https://www.ruby-forum.com/topic/185481 | |
#Hit me up if you have questions! <3 | |
#So in the example below, when I call FilmShoot.filming, the method throws an error because it believes "budget" to be nil. | |
class FilmShoot | |
attr_accessor :budget, :actors, :day_of_shooting | |
attr_reader :director | |
def initialize(director, budget, actors) | |
@director = director | |
@budget = budget | |
@actors = actors | |
@day_of_shooting = 0 | |
end | |
def filming | |
if budget == 0 | |
day_of_shooting += 1 | |
puts "COME ON GUYS IT IS THE #{day_of_shooting} DAY OF SHOOTING. LET'S WRAP IT UP AND NOT HAVE THIRTY TAKES PER SCENE!! MONEY DOESN'T GROW ON TREES." | |
beg_for_more_money | |
else | |
budget -= 1000 | |
day_of_shooting += 1 | |
puts "Jesus Christ, it's already day #{day_of_shooting}? I feel like I've been on this set forever. Where's all my money going?" | |
end | |
end | |
private | |
def beg_for_more_money | |
budget += 50_000 | |
end | |
end | |
#REFACTORED: This works now because I'm directly referencing the instance variable--there's no more Ruby confusion! | |
#You could also call @budget, @day_of_shooting and it would work, but the way I've refactored below is preferable convention-wise. | |
class FilmShoot | |
attr_accessor :budget, :actors, :day_of_shooting | |
attr_reader :director | |
def initialize(director, budget, actors) | |
@director = director | |
@budget = budget | |
@actors = actors | |
@day_of_shooting = 0 | |
end | |
def filming | |
if self.budget == 0 | |
self.day_of_shooting = day_of_shooting + 1 | |
puts "COME ON GUYS IT IS THE #{day_of_shooting} DAY OF SHOOTING. LET'S WRAP IT UP AND NOT HAVE THIRTY TAKES PER SCENE!! MONEY DOESN'T GROW ON TREES." | |
beg_for_more_money | |
else | |
self.budget = budget-1000 | |
self.day_of_shooting = day_of_shooting + 1 | |
puts "Jesus Christ, it's already day #{day_of_shooting}? I feel like I've been on this set forever. Where's all my money going?" | |
end | |
end | |
private | |
def beg_for_more_money | |
self.budget = budget + 50_000 | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment