Hey ,
How do I get IRB?? How is this different from using SSH ?
Also, can I have different classes in a file, that are not subclasses of one another? Using your example, could I have a class in that file that was not a subclass of Greet?
Thanks,
Vidhi.
···
-----Original Message-----
From: Brian Schröder [mailto:ruby@brian-schroeder.de]
Sent: Friday, February 11, 2005 9:37 AM
To: ruby-talk ML
Subject: Re: new to this language
On Sat, 12 Feb 2005 02:15:18 +0900 Jim Menard <jimm@io.com> wrote:
Vidhi,
Welcome to Ruby.
> 1) Just like in C++ you have a .h and a .cpp file , In this language how
> would you store your file. In other words if I open emacs and want to
> write a very simple small class in what format would I save this file ?You store all your code in .rb files. There is no separate header file. You
declare and define a class in one place, just like in Java. (That's not
strictly true; in Ruby you can "re-open" a class and add more methods later.
Don't worry about that yet.)superclass.rb:
class Superclass
attr_accessor :super_instance_var
def initialize
@super_instance_var = 42
end
endmyclass.rb
require 'superclass'
class MyClass < Superclass
attr_accessor :my_instance_var
def initialize
@my_instance_var = 'hello'
end
endanother.rb
require 'myclass'
mc = MyClass.new
puts mc.my_instance_var
puts mc.super_instance_var> 2) How do you compile your code? What is the syntax?
Ruby is an interpreted language, which means that it doesn't need to be
compiled before you run it. To run "another.rb" above, typeruby another.rb
> 3) Do you need a main and a makefile ? I am sure you would need a main
> to test it . If yes how do you save the main? In what format?You don't need a main method. All Ruby code is executed as it is seen by the
interpreter. Some of the code above (superclass.rb and myclass.rb) define
classes and some of the code (another.rb) creates an instance of a class and
prints some output.
one thing I want to add, is that you need not create a seperate file per class. You can as well group classes by functionality and put multiple classes in one file. (I think using one file per class is a java idiom).
first.rb
class Greet
def initialize(name)
@name = name
end
end
class GreetEnglish < Greet
def greetme
puts "Hello #{name}"
end
end
class GreetGerman < Greet
def greetme
puts "Hallo #{name}"
end
end
class GreetSpanish < Greet
def greetme
puts "Hola #{name}"
end
end
greeters = [GreetEnglish, GreetGerman, GreetSpanish]
greeter = greeters[rand(greeters.length)].new
greeter.greet
is perfectly reasonable and allowed. (Though maybe not two good design, and you can shorten this alot when you have learned about dynamic programming).
And additionally, if you want to play with the language use irb, the ruby interactive shell.
good luck and enjoy ruby,
Brian