I ran into some confusion when messing around with a sample program I created that creates new instances of a class Car and names the car. I wanted to store my list of “funnynames” in an array and have my naming method grab a random name from the array via my “name” method which would be “initialized” (using the initialize method) upon creation of each new instance of the Car class. Blahblahblah. So my problem: class variables work for me, but instance variables don’t! I couldn’t find much on instance variables, because everything seemed to start talking about instance methods once they mentioned instance variables. It seemed like everyone was reluctant to point out that INSTANCE VARIABLES ARE INVISIBLE!?!?! outside of the class. You can’t access them outside of the class unless you use an accessor method (easiest) or other method. If I’m wrong here, someone correct me. But to my knowledge, that’s how it works. However, if you store the data you’d like to access in a class variable, it works! Unfortunately. Since it’s so easy, but a bad idea, from what I hear. Inheritance happens. Right?
And to think… these three ways to do the same thing in Ruby (minus side effects in the future if I were to use the class variable) aren’t even the only ways to do this.
It’s interesting for me that I discovered this basically on my own when developing a simple practice program. Wee!
class Car
def name
@funnynames=%w[bob judy mabel wiener]
puts "Your car's name is #{@funnynames[rand(4)]}!"
end
end
#defining array within method
class Car
@@funnynames=%w[bob judy mabel wiener]
def name
puts "Your car's name is #{@@funnynames[rand(4)]}!"
end
end
#array as a class variable (thus I'm able to access it)
class Car
@funnynames=%w[bob judy mabel wiener]
class << self #makes the accessor method relevant to the class rather than a single instance
attr_accessor :funnynames
def name
puts "Your car's name is #{Car.funnynames[rand(4)]}!"
end
end
# Voila! More on this later as I continue to learn the in's and out's
Currently Computing: Revisiting my text analyzer with the use of ARGV[] to analyze files via the command line rather than hardcoding in the file to access within the program. SO cool! Then back to more OO sample programs. Rails will happen. I’m just busy nerding out on Ruby itself for the time being.