r/learnruby • u/Equality7221 • May 24 '17
Having trouble with classes
I'm going through the OdinProject coursework and have been having trouble with the OOP projects that ask you to use classes to make TicTacToe & Mastermind. I'm having a really hard time making the classes communicate with each other in their own files but in general also just having instance variables hold necessary information without having to add them as parameters for the initialization method.
Here is an example of what I mean. I made a method to randomize the computer's array for the player in Mastermind, but I need the "code" variable to be an instanced variable so that it can interact with other things outside the randomize method:
def randomize
#8 colors
colors=%w{red green blue white black purple yellow orange}
$code=[]
until $code.length==4 do
$code.push(colors[Random.rand(0..7)])
end
puts "-"* 55
end
(I turned code into a global variable but i know that's not a real OOP fix)I'm not sure what other resources to look into; I have "Beginning Ruby" and "Practical Object Oriented Design in Ruby", I've done the exercises on CodeAcademy, Treehouse, CodeSchool, RubyMonk's primer course (ascent is over my head at this point) and the coursework from Odin up to this point also. Whenever they go over classes it feels like it's always:
class Dog
def initialize(name)
@name=name
end
def bark
puts "ruff"
end
end
Greg=Dog.new("Greg").bark"okay now you know all about classes"
But that could just be frustration. Any pointers would be greatly appreciated.
View all comments
Show parent comment
1
u/Equality7221 Jun 09 '17
This def. helped! Prior to this I've been pretty strict about only creating instance variables in the initialize method. I actually found another article that suggested creating an empty instance variable in the initialize method and then assigning it to w/e you needed at the end of your method.
Thanks for your input, still a lot to unravel, but after that hang up it started to flow a little more.