Wednesday, 3 September 2008

Ruby Pocket Reference By Michael Fitzgerald

Just now i completed reading Ruby Pocket Reference by Michael Fitzgerald

Good book by Michael Fitzgerald

I want to share few important quotations from this book.

1) Ruby is an open source, object-oriented programming language created by Yukihiro “Matz” Matsumoto. First released in Japan in 1995, Ruby has gained worldwide acceptance as an easy-to-learn, powerful, and expressive language, especially since the advent of Ruby on Rails, a web application framework written in Ruby (http://www.rubyonrails.org). Ruby’s core is written in the C programming language and runs on all major platforms. It is an interpreted rather than compiled language. For more information on Ruby, see http://www.ruby-lang.org.

2) The Bignum class is used to hold integers larger than Fixnum can hold. Bignums are created automatically if any operation or assignment yields a result too large for Fixnum. The only limitation on the size integer Bignum can represent is the available memory in the operating system.

3) Ruby variables are not declared nor statically typed. Ruby uses duck typing, a kind of dynamic typing.

4) Symbols

Ruby has a special object called a symbol. Symbols are like placeholders for identifiers and strings; they are always prefixed by a colon (:), such as :en and :logos. Most importantly,only one copy of the symbol is held in a single memory address, as long as the program is running. You don’t directly create a symbol by assigning a value to one. You create a symbol by calling the to_sym or intern methods on a string, or by assigning a symbol to a symbol:

name = "Brianna"
name.to_sym # => :Brianna
:Brianna.id2name # => "Brianna"
name == :Brianna.id2name # => true

5) Pseudovariables

A pseudovariable is an object that looks like a variable, acts like a constant, and can’t be assigned a value.









Pseudo VariablesDescription
falseLogical or Boolean false; instance of FalseClass.
nilEmpty, uninitialized, or invalid; always false, but not the same as zero; object of NilClass.
selfCurrent object (receiver invoked by a method).
trueLogical or Boolean true; instance of TrueClass.
_ _FILE_ _Name of current source file.
_ _LINE_ _Number of current line in the current source file.


6) Ranges

Ruby supports ranges by means of the .. (inclusive) and ... (exclusive) operators. For example, the range 1..12 includes the numbers 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, inclusive. However,in the range 1...12, the ending value 12 is excluded; in other words, the effective numbers are 1, 2, 3, 4, 5, 6, 7, 8, 9,
10, 11.

The === method determines whether a value is a member of,or included in a range:

(1..25) === 14 # => true, in range
(1..25) === 26 # => false, out of range
(1...25) === 25 # => false, out of range (... used)

You can use a range to do things like create an array of digits:
(1..9).to_a # => [1, 2, 3, 4, 5, 6, 7, 8, 9]

You can also create a range like this:
digits = Range.new(1, 9)
digits.to_a # => [1, 2, 3, 4, 5, 6, 7, 8, 9]

7) Methods can take arguments

Example:

def repeat( word, times )
puts word * times
end
repeat("Hello! ", 3) # => Hello! Hello! Hello!
repeat "Goodbye! ", 4 # => Goodbye! Goodbye! Goodbye!
Goodbye!

8) If a method name ends with a question mark (?), such as eql?, it means that the method returns a Boolean—true or false.

If a method name ends in an exclamation point (!), like delete!, it indicates that the method is destructive, meaning it makes in-place changes to an object, rather than to a copy; that is, it changes the object itself.

9) Default Arguments

The repeat method shown earlier has two arguments. You can give those arguments default values by using an equals sign followed by a value. When you call the method without arguments, the defaults are used automatically. Redefine repeat with default values: Hello for word, and 3 for times.Call it first without arguments, then with them.

def repeat( word="Hello! ", times=3 )
puts word * times
end

repeat # => Hello! Hello! Hello!
repeat( "Goodbye! ", 5 ) # => Goodbye! Goodbye! Goodbye!
Goodbye! Goodbye!

10) Variable Arguments

You can be flexible about the number of arguments that a method has, because Ruby lets you pass a variable number of arguments by prefixing an argument with a splat (*):

def num_args( *args )
length = args.size
label = length == 1 ? " argument" : " arguments"
num = length.to_s + label + " ( " + args.inspect + " )"
num
end

puts num_args # => 0 arguments ( [] )
puts num_args(1) # => 1 argument ( [1] )
puts num_args( 100, 2.5, "three" )
# => 3 arguments ( [100, 2.5, "three"] )

11) Aliasing Methods
Ruby has a keyword, alias, that creates method aliases.Aliasing means that you in effect create a copy of the method with a new method name, though both method invocations will point to the same object.

Example:

def greet
puts "Hello, baby!"
end

alias baby greet # alias greet as baby

greet # call it
Hello, baby!
baby # call the aliased version
Hello, baby!

12) A block in Ruby is more than just a code block or group of statements. A Ruby block is always invoked in conjunction with a method, as you will see. In fact, blocks are closures,sometimes referred to as nameless functions. They are like a method within another method that refers to or shares variables with the enclosing or outer method. In Ruby, the closure or block is wrapped by braces ({}) or by do/end, and depends on the associated method (such as each) to work.

13) The yield statement
A yield statement executes a block associated with a method.

class YieldDemo

def gimme
if block_given?
yield
else
puts "I'm blockless!"
end
end

end

y=YieldDemo.new
y.gimme { print 'hi'}

y.gimme

Prints:
hiI'm blockless!

14) You can convert a block passed as a method argument to a Proc object by preceding the argument name with an ampersand (&) as follows:

def return_block
yield
end

def return_proc( &proc )
yield
end

return_block { puts "Got block!" }
return_proc { puts "Got block, convert to proc!" }

15) The until Statement

As unless is a negated form of if, until is a negated form of while. Compare the following statements:

weight = 150
while weight < 200 do
puts "Weight: " + weight.to_s
weight += 5
end

Here is the same logic expressed with until:

weight = 150
until weight == 200 do
puts "Weight: " + weight.to_s
weight += 5
end

16) An alternative to the for loop is the times method (from class Integer):

12.times { |i| print i, " " } # => 0 1 2 3 4 5 6 7 8 9 10 11

17) In an object-oriented programming language like Ruby, a class is a container that holds properties (class members) such as methods and variables. Classes can inherit properties from a parent or superclass, creating a hierarchy of classes with a base class at the root or top. In Ruby, the base class is Object.

Ruby uses single inheritance—that is, a Ruby class can inherit the properties of only one parent class. (Multiple inheritance, as is used in C++, allows a class to inherit from more than one parent.) You can define more than one class in a single file in Ruby. A class itself is an object, even if you don’t directly instantiate it. Classes are always open, so you can add to any class, even a built-in one.

A class is defined with a class keyword, and the definition concludes with an end:

class Hello

def initialize( name )
@name = name
end

def hello_matz
puts "Hello, " + @name + "!"
end

end

hi = Hello.new( "Matz" )
hi.hello_matz # => Hello, Matz!

18) To add a method to an existing class, such as the built-in class Array, specify the following:

class Array
def array_of_ten
(1..10).to_a
end
end
arr = Array.new
ten = arr.array_of_ten
p ten # => [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

19) instance variable is a variable that is available from within an instance of a class, and is limited in scope because it belongs to a given object. An instance variable is prefixed by a single at sign (@).

20) Accessors
Ruby simplifies the creation of getters and setters by metaprogramming with the methods attr, attr_reader, attr_writer, and attr_accessor, all from the Module class. The attr method creates a single getter method, named by a symbol, with an optional setter method (if the second argument is true):

21) A class variable is shared among all instances of a class, so only one copy of a class variable exists for a given class. In Ruby, a class variable is prefixed by two at signs (@@). You must initialize a class attribute before you use it, such as @@times = 0.

22) Singletons

Another way you can define class methods is by using a class within a class and self—a singleton class. In basic terms, a singleton is designed so that it can only be instantiated once.

It is often used like a global variable. Ruby has a class for defining singleton objects; see http://www.ruby-doc.org/core/ classes/Singleton.html. Consider this example:

class Area
class << self
def rect( length, width, units="inches" )
area = length*width
printf( "The area of this rectangle is %.2f %s.",area, units )
sprintf( "%.2f", area )
end
end
end

Area.rect(10, 10) # The area of this rectangle is 100.00 inches.=> "100.00"

23) When a child class inherits or derives from a parent, it has access to the methods and properties of the parent class. Inheritance is accomplished with the < operator.

24) Without hesitation,it can be said that the hymns of the vast vedic literature were in existence at least 4000 years before christ.

25) Modules and Mixins

In addition to classes, Ruby also has modules. A module is like a class, but it cannot be instantiated like a class. A class can include a module so that when the class is instantiated, it gets the included module’s methods and so forth. (The include method comes from the Module class:
http://www.ruby-doc.org/core/classes/Module.html.) The methods from an included module become instance methods in the class that includes the module. This is called mixing in, and a module is referred to as a mixin.

module Dice
# virtual roll of a pair of dice
def roll
r_1 = rand(6); r_2 = rand(6)
r1 = r_1>0?r_1:1; r2 = r_2>0?r_2:6
total = r1+r2
printf( "You rolled %d and %d (%d).\n", r1, r2, total )
total
end
end

class Game
include Dice
end

g = Game.new
g.roll

26) The Array class is one of Ruby’s built-in classes. Arrays are compact, ordered collections of objects. Ruby arrays can hold objects such as String, Integer, Fixnum, Hash, Symbol,even other Array objects.

27) array.map { |item| block }

Invokes block once for each element of self. Creates a new array containing the values returned by the block.

28) array.reject! { |item| block }
Deletes elements from array for which the block evaluates to true, but returns nil if no changes were made. Equivalent to Array#delete_if.

29) A hash is an unordered collection of key-value pairs that look like this: "storm" => "tornado". A hash is similar to an Array,but instead of a default integer index starting at zero, the indexing is done with keys that can be made up from any Ruby object. In other words, you can use integer keys just
like an Array, but you also have the option of using any Ruby object as a key, even an Array!

30) Ruby Gems

RubyGems is a package utility for Ruby (http://rubyforge.org/projects/rubygems). It was written by Jim Weirich. It installs Ruby software packages, and keeps them up to date. It is quite easy to learn and use, even easier than tools like the Unix/Linux tar utility (http://www.gnu.org/software/tar) or Java’s jar utility (http://java.sun.com/j2se/1.5.0/docs/tooldocs/windows/jar.html).

31) Rake
A build tool helps you build, compile, or otherwise process files, sometimes large numbers of them. Rake is a build tool like make (http://www.gnu.org/software/make) and Apache ant (http://ant.apache.org), but it is written in Ruby. It is used by Ruby many applications, not just Rails. Rails operations use Rake frequently, so it is worth mentioning here.

Hope you enjoy reading this book.

About the Author

Michael Fitzgerald is Director of Education for AtTask, a leader in online project management software. He is the author of Learning Ruby, Ruby Pocket Reference, XML Pocket Reference, Third Edition with Simon St. Laurent, XML Hacks, and Learning XSLT, all published by O'Reilly. He is also the author of Building B2B Applications with XML: A Resource Guide and XSL Essentials (both by John Wiley & Sons). His books have been translated into Spanish, French, German, Japanese, and Chinese. He has also been a regular contributor to XML.com. Michael likes to ski, ride and train horses, and spend lots of time with his family.

No comments: