IMP1 Ruby Tutorial
OmegaDev :: Coding Plaza :: RGSS2 (VX) :: RGSS2 Tutorials
Page 1 of 1
IMP1 Ruby Tutorial
First off, download the Ruby Installer. It'll allow you to try out ruby by yourself.
Ruby Tutorial V - Classes
Ruby Tutorial V - Classes
Things to know:
The way that can be described is not the right way.
First off, in Ruby, everything is sorted out into Classes. These can be as simple as:
- Code:
class Any_Name_starting_With_A_Capital
def initialize
puts "Hello World" # Cliché I know. But comforting :)
end
end
- Code:
any_variable = Any_Name_starting_With_A_Capital.new
- Code:
class IMP1_Super_Class
def poke
puts "*squeal*"
end
end
Now, back to the different types of variables, since we now know what classes are. There are:
Local Variables
These are only used in a method (or block). They start with a-z or an underscore (_).
Instance Variables
These can be accessed throughout a class. They start with an at sign (@).
Class Variables
These are accessed throughout every instance of the class, and they must be initialized in the class (outside of a method, usually before initialize). If it is changed then it is changed for every instance of the class. They start with dual-at signs (@@)
Global Variable
Global variables in Ruby are accessible from anywhere in the Ruby program. However, Use of global variables is strongly discouraged. The problem with global variables is that, not only are they visible anywhere in the code, they can also be changed from anywhere. This can make tracking bugs difficult. They start with a dollar sign ($).
Okay, they all are pretty straight forward. All that is, except the class variables, I always had the hardest time thinking when they'd ever be useful. In this next example I'll not only use them I'll also use a Sub Class. Take a look:
- Code:
class Car
@@wheels = 4
@@cars_produced = 0
def initialize
@@cars_produced += 1 # a += 1 is the same as a = a + 1. It works with - * / % too
end
def drive
puts "vroooom!"
end
def self.amount # see *1
return @@cars_produced
end
end
class Strecth_Limo < Car # Using Class1 < Class2 means Class1 has everything Class2 has,
# but you can add specific Class1-only stuff too.
@@wheels = 8
def drive # note that Car already has this class, but I've overwritten it.
# Methdods in Sub Classes overwrite their parent classes.
puts "chugga chugga"
end
def turn_on_TV
puts "done."
end
end
Homework:
Make sure everything I've said so far makes sense and, if any of it doesn't, read through again and then ask for clarification.
Good Hunting.
NEXT TIME: Arrays
IMP1- Coding Moderator
- Posts : 503
Gald : 1399
Stats
Cookies: 5
OmegaDev :: Coding Plaza :: RGSS2 (VX) :: RGSS2 Tutorials
Page 1 of 1
Permissions in this forum:
You cannot reply to topics in this forum
|
|