Ruby: day 2

On to day 2. I can happily tell you that the book is very well written and gives just enough explaining of basic Ruby but still lets you figure out how different Ruby components work. There are enough clear examples in the book to complete the exercises in minimal time.

First lesson of day 2: in Ruby you don’t need to write a class to define a function. Yay!
>> def show_happyness
>> true
>> end

Syntactic sugar is a name for functions that make code easier to read and write. Ruby has several nice array functions implementing this. Like in Java, array[0] will give the first element of the Array array. However, array[-1] will give the last element of the Array array, this opens a world of Array handling possibilities. Also, Arrays don’t need to contain values of the same type.
>> a = []
>> a[0] = 'zero'
>> a[1] = 1
>> a
=> ["zero", 1]

Symbols are identifiers preceded by a colon, like :symbol. Identical symbols are always the same physical object. I’m sure this will be useful time or another.

Code blocks are functions without a name. You can for instance pass them as a parameter in a function. Code blocks are represented in braces {} or do/end. When using multiple lines do/end is the preferred format.

>> 3.times {puts 'Ruby'}
=> Ruby
=> Ruby
=> Ruby

Until now I had executed every piece of code from the command line, about time for change! Saving a file in the .rb format enables you to execute it from the command line.

ruby hello.rb
'Hello World'

Next, some insight in Ruby’s metamodel. In the end every class inherits from Object. If you look at the number 4, it is an instance of Fixnum, which inherits from Integer, which inherits from Numeric. Numberic is an instance of the class Class which inherits from Module, which inherits from Object.
It is conventional to start class names with capital letters and use CamelCase to denote capitalization (FancyClassName). Instance variables are preceded by ‘@’, and class variables are preceded by ‘@@’ (limited to one value per class). Instance variables and method names begin with lowercase letters and use the underscore style (my_method_name). Constants are written in all caps (VERY_CONSTANT_CONSTANT).

Many of these conventions I have seen and used before, but the ‘@’ and ‘@@’ are new for me. They make sense though, because ‘normally’ in Java you would declare a variable by naming its type and then its name. Since you don’t have to name a variable type when declaring a variable in Ruby, something else has to be used to state it is a variable.


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s