Jump to content

Check out our Community Blogs

Register and join over 40,000 other developers!

Recent Status Updates

View All Updates

- - - - -

Ruby, Classes


  • Please log in to reply
No replies to this topic

#1 RhetoricalRuvim


    JavaScript Programmer

  • Expert Member
  • PipPipPipPipPipPipPip
  • 1311 posts
  • Location:C:\Countries\US
  • Programming Language:C, Java, C++, PHP, Python, JavaScript

Posted 27 August 2011 - 04:31 PM

In this tutorial, we'll learn about classes.

Oh no! It's not even September yet, and we already have to go to class? No, classes in programming are different from classes at school.

A class is basically a format for a type of object. Classes can have functions and constants. Instances of classes usually have variables.

  • Defining A Class
  • Instance Variables
  • Class Constants
  • Example Program

Defining A Class
To define a class with name name, you just have to type this:
class [COLOR=#CCCC55]name[/COLOR] 
    ...define some things here...

Simple, huh? But you can also define functions withing a class.

To define function fxn inside our class, we just have to define the class with the function:
class [COLOR=#CCCC55]name[/COLOR] 
    def [COLOR=#FF5511]fxn[/COLOR] 
        ...do something...

Let's try making a class that would say hello.

Class Hello
class SayHello 
    def say name 
        puts "Hello #{name}!" 

Now here's how we use the class:

We make a new instance of that class and assign that to a variable:
sh= SayHello.new

Then we use the class's function:
sh.say "World"

That code should print "Hello World!"

We Can Use More Than One Instance Of A Class
Let's use the same class.

Make a new instance of the class and save it to `a`:
a= SayHello.new

Make another instance and save it to `b`:
b= SayHello.new

Say hello to Andrew using `a`:
a.say "Andrew"

Say hello to Barney using `b`:
b.say "Barney"

So every time we want to say hello to Andrew, we have to tell his name to the say() function. But what if we wanted our class to keep track of the name, so that we only have to tell it once and it would remember it?

Let's redefine the class using global variables.

class SayHello 
	def initialize name 
		$name= name 
	def say 
		puts "Hello #{$name}!" 

Now we use the class:
a= SayHello.new "Andrew" 
b= SayHello.new "Barney"

And now it's time to say hello to those two people:

The above code should output "Hello Barney!\r\nHello Barney!\r\n"

What? But...we used different names for the different classes; what's with that?

There are two (if not more) problems with using global variables like that.

  • The variables are always going to have the value that was last set for that variable; for example, we used @name and the value that was last set for @name was "Barney" , so we got 'Hello Barney!' both times.
  • Other parts of the code might already be using a variable with that name; what if the main code is already using @name for something else?

So what should we do? Well, there are these things called instance variables.

Instance Variables
Instance variables are kind of like local variables for a class, but, unlike local variables - which need to be redefined every time a function is called - instance variables keep their values while the class exists.

Also, instance variables have values that are unique to that class; in other words, if that variable is set to one value in one instance of the class, it doesn't necessarily mean that that variable will be the same in another instance of that class.

Instance variables can't be accessed outside the class.

They are defined like local variables, except that there needs to be a leading '@' symbol in the variable name, in any reference to that variable.

So to set an instance variable, with name name and value value, we do something like this:
@[COLOR=#884488]name[/COLOR]= [COLOR=#339944]value[/COLOR]

Our New Class
class SayHello 
	def initialize name 
		@name= name 
	def say 
		puts "Hello #{@name}!" 

Okay, let's now use that class.

Make instances of the class:
a= SayHello.new "Andrew" 
b= SayHello.new "Barney"

Now let's use the say() function:

The output, now, should be "Hello Andrew!\r\nHello Barney!\r\n"

Sometimes it might be useful to define constants for a class.

Class Constants
A constant is kind of like a variable, except that it doesn't change, over the course of the program's execution. So once you define a constant, you can't change it.

So why not just use variables?

Well, you can, but how is code outside the class supposed to access them? You could use functions, but if the return value's not going to change anyway, why not just use a class constant? (Calling a function usually takes more time than using a value from a constant.)

To define a class constant, named Name, with the value value, you would use:
[COLOR=#44FFAA]Name[/COLOR]= [COLOR=#66EE88]value[/COLOR]

How is that different from defining a local variable? The difference in definition is that the name of a class constant starts from a capital letter, while the name of a local variable starts with a lower-case letter.

class SomeClass 
	SomeConstant= 1 
	def print_some_constant 
		puts "#{SomeConstant}" 

This code would print "1" to the screen:
a= SomeClass.new 

So would this code:
puts "#{SomeClass::SomeConstant}"

We wouldn't use constants in our example program, but I think you got the point.

Example Program

The Code
# Let's define a class. 
class MyClass 
	# Class names in class definitions usually start with 
	# capital letters. 
	def initialize the_name 
		# When we initialize the class, we need to set the @the_name 
		# variable to the initialize argument. 
		@the_name= the_name 
	def say_hello 
		# This function outputs 'Hello ' + @the_name + '!' 
		puts "Hello #{@the_name}!" 
	def set_name new_name 
		# This function sets the @the_name instance variable. 
		@the_name= new_name 
	def get_name 
		# This function returns the @the_name instance variable. 

# Let's make a new instance of that class. 
c= MyClass.new 'Wendy' 

# Now let's say hello. 

# Okay, let's change the name to Sandy 
c.set_name 'Sandy' 

# Say hello again. 

# Now let's get the name. 
some_name= c.get_name 

# And let's output that name. 
puts some_name 

# Wait for return key press. 

The Output
Posted Image

(Fullsize Screenshot)

First Tutorial:
Hello World Introduction

Previous Tutorial:
Variables and Functions

Next Tutorial:
More About The Language

Edited by RhetoricalRuvim, 27 August 2011 - 10:04 PM.

  • 0

Also tagged with one or more of these keywords: ruby

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download