SEARCH
0-9 A B C D E F G H I J K L M N O P Q R S T U V W X Y Z
Prev | Current Page 421 | Next

Ola Bini

"Practical JRuby on Rails Web 2.0 Projects: Bringing Ruby on Rails to Java"

There exists an explicit true value too, though.
What makes it more interesting is that nil, true, and false are all instances of classes, and are
objects in their own right. That means you can add new methods to them if you want. nil is
the only instance of the class NilClass, true is the only instance of TrueClass, and false is the
only instance of FalseClass.
APPENDIX A ?–  RUBY FOR JAVA PROGRAMMERS 295
Classes and Modules
Ruby is a pure object-oriented language. That means that everything is an instance of a class.
All classes are also modules, but modules can exist on their own. There are two main usages
for modules: they act as namespaces and they allow you to mix behavior into classes. That
second feature is the reason why Ruby can be single inheritance and not need interfaces.
Use this code to define a new module:
module Foo
end
Do this to define a new class:
class Bar
end
Use this code to define a class with a superclass:
class MyString < String
end
To define a class inside the namespace of a module, open up that module and define the
class in it:
module Foo
class MyString
end
end
To refer to that class, use the double-colon syntax mentioned earlier:
Foo::MyString.new
Defining Methods
All methods must exist within either a module or class. If you define a method at the top level,
you will in fact define it on the Singleton class of the top-level object.
To define a new method, use the keyword def:
class Foo
def hello
end
end
Do this to define a method that takes arguments:
def hello(arg1, arg2)
end
Use this code to define a method that takes optional arguments:
def hello(arg1, arg2 = "foo")
end
APPENDIX A ?–  RUBY FOR JAVA PROGRAMMERS 296
An optional argument needs to have a default value.


Pages:
409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433