Classes, their methods, their variables etc. have been a very new concept for me and also something that has been difficult for me to fully grasp.
I'm teaching myself Ruby, and this topic is frustrating so I decided to look at things differently.
I realize I've been using classes, instance variables and instance methods from day one.
Example
**String - class
"Hi my name is...." - instance of the String class.
.length - an instance method for the String class that I can call on the above instance.
"Hi my name is....".length => 17
I could create
x = String.new("Hi")
But I can also create
x = "Hi"
Both are the same
If I created a cat class
class Cat
attr_reader :name
def initialize(name)
@name = name
end
end
jinx = Cat.new("Jinx")
print jinx.name => Jinx
Here we have
Cat - class
"Jinx" - instance of the Cat class.
.name - an instance method for the Cat class.
Two questions
Is this a good way to view classes? When I get to bigger problems like creating a tic tac toe game (which I am doing now) with multiple classes I feel over my head at times. It's frustrating, cause I feel stupid (maybe I should get used to that), but I'm beating myself up here. I've had a very easy time going on code wars and solving a ton of problems with a single method. I know somewhere if I can relate that to classes, I'd better understand. Is looking at the solution code when stuck the best way to teach myself? I don't have anyone to ask and I want to retain as much info as possible.
Second, how does Ruby know a String is a String, an Array an Array, a Hash a Hash so I can define those variables and not call .new like I would for Cat? Is it just the syntax "" for string, [] for array, {} for hash so it assumes that's what we are talking about?