Ruby Symbols

Symbols in ruby are like labels. They are also strings, however unlike ruby string objects which are mutable (modifiable post instantiation),  symbols are immutable strings and belong to the Symbol class. They are used where immutability, performance and space are key and the richness of the string class is not required.

There are many ways to instantiate a symbol object.

:ruby and :”ruby” are the same literal.

%s{ruby}

:’United States of America’ – quotes should be used when the symbol has spaces

x = “string”

symbol = :”#{x}”

The ‘intern’ or ‘to_sym’ methods can be used to convert a String object to a Symbol object. With the methods ‘to_s’ and its alias ‘id2name’: a Symbol object can be converted back to a String.

var = “string”

sym = var.intern

sym = var.to_sym

var = sym.to_s

var = sym.id2name

Symbols enable us to use a single memory location to represent a literal, thus saving memory in the long run. A String would occupy a different memory location each time it is instantiated, which means two strings can hold the same content yet be completely distinct objects and use up multiple amounts of space. This becomes an issue especially if we want to use the same literal repeatedly during the course of a program. With symbols, distinct symbol objects will always have different content. Different strings with the same content will all be converted to the same Symbol object.  Therefore symbols are the better choice for unique identifiers.

Eg: if we want to use the word ‘ruby’ and create assignments as string objects;

gem = “ruby”

rails_language = “ruby”

calling object_id on each of the variables shows that they are pointing to different  “ruby” string objects.  When assignments are created using the word ‘ruby’ as a symbol;

gem = :ruby

rails_language = :ruby

they point to the same ruby object.

symbols1

Using ‘intern’ and ‘to_s’ methods to demonstrate that different string objects with the same content will convert to the same symbol object (as shown in The Ruby Programming Language).  This is covered above, however, I present it here since it’s pretty neat to use the ‘intern’ and ‘to_s’ methods in the proof.

symbols2

In addition to economies of storage, symbols also offer better performance when used as unique identifiers. This is due to the ruby interpreter. The way the ruby interpreter works is by storing symbols referencing the names of all the classes, methods and variables that have been defined, in a table. If it needs to refer to a method name for example, it does so by its position in the table. This way, only integer operations are carried out and string operations are avoided. Therefore, with a unique identifier for example, it is much faster to carry out comparisons etc. if they are defined as symbols than if they were string objects.

Although the Symbol class is a computationally economical option than String class, some String class methods such as length, size, the comparison operators and the [] and =~ operators are defined in the Symbol class too, enabling the use of symbols to a certain extent as strings. This makes a symbol an immutable string which is not garbage-collected.

Using irb, we can call the methods ‘all_symbols.size’ on Symbol and find out how many symbol objects already exist in ruby. When we define a variable ‘my_symbol’ for instance, that variable is stored as a symbol in the symbol table and if we call ‘all_symbols.size’ again on Symbol we notice that the size has increased by 1 as shown below.

symbols3

Advertisements

Ruby Strings

A string object in ruby can be created by using either double quotes, “Hello World”, or single quotes, ‘Hello World’. Both are objects which is a sequence of 8-bit bytes in memory belonging to the class String. Since this sequence of memory is used to represent characters of a spoken language: it is referred to as a string literal (the string literal is – Hello World and does not include the quotes).

string1

What’s the difference between ‘….’ and “….” ?

Single quotes allow for the simplest form string literal. It does not support substitution. It only supports two escape sequences ( \’ and \\ ). Double quotes on the other hand not only support substitution but also many escape sequences. Although this is not obvious from the string literal example above, if we try to create a string literal such as ‘My name is Suchitra and I’m learning ruby’ we can run into these limitations depending on how we implement it.

If we try to implement it just as above we can do so by escaping \’ in I’m and it works fine.

string2

However, if we want to insert the name as a variable, single quotes don’t support substitution but double quotes do.

string3

Additionally double quotes also support other escape sequences such as \” – Double quote, \\ – single backslash, \a – bell/alert, \b – backspace, \r – carriage return, \n – newline, \s – space, \t – tab.

With ruby strings, it is possible to perform certain string operations using what are usually arithmetic operators.

  1. Adding two strings (string concatenation) can be performed by using the + operator: puts ‘Sam, ‘ + ‘I am.’ Note however that, only a string can be added to another string. So if we try:  puts‘19’ + 75 we are told a number cannot be added to a string.
  2. The multiplication operator can be used where an object is required to be used repeatedly such as puts ‘etc.’*3 which would mean output the string etc. three times or output three sets of the string etc. But don’t expect 3*’etc.’ to work because we are asking for ‘etc.’ sets of 3 which is senseless.

string4

 

Numbers in Ruby

Like all things in ruby, numbers too are objects. They are instances of the Numeric class. If the number is an integer it will belong either to the Fixnum or Bignum class. If it is a float it belongs to the Float class. So how do we find out? Let’s call our friend irb and see,

num1

As seen from above, we enter an integer number (in this case 7). In ruby this number is now an object. In order to find out what class this object belongs to we enter 7.class and as can be seen, irb evaluates it to be Fixnum. Similarly, if we enter a floating point number, we see that it belongs to class Float. If we assign 7 to a variable “a”, then “a” points to an object of type Fixnum and if we re-assign 7.0 to it, it then points to an object of type Float.

An object is an instance of a class. That is, the class is the generic (in this case number) and an object (7) is a specific (just like class: human, object: Suchitra). So an object inherits various traits from its class such as methods and we are able to perform various computations. For example, we can add two integers and get an integer answer; we can add two floating numbers and get a floating number answer and so on.

num2

Like all of us have ancestors, ruby classes too have ancestor classes from which they inherit properties. If you want to check what the ancestor classes are of the Fixnum class, you can do so by typing,

num3

Now we can see the entire list of parent classes of Fixnum, going all the way back to BasicObject (BasicObject is the parent class of all classes in ruby).

Experimenting with number objects: Since number objects are armed with various methods, we can do all kinds of manipulations in ruby. We can add, subtract, square, divide etc. etc. etc……………

However there are a few things that I have come across so far, that are done differently in ruby when dealing with numbers which would be good to keep in mind. For example,

1. When dividing two numbers, the division operator depends on the class of the operands. If both values are integers then truncating-integer division is performed. If either value is a Float then floating-point division is performed.

num4

2. With integer division, -a/b = a/-b but may not equal –(a/b)

num5

As can be seen -2/1 = 2/-1 = -(2/1) = -2, however, -5/2 = 5/-2 = -3 and –(5/2) = -2.  In ruby with integer division truncation is towards negative infinity where as with languages like C/C++  truncates towards zero.  In this example, the floating point result of -5/2 = 5/-2 = -2.5 which is truncated to -3. However with –(5/2), it first performs the floating point division of  5/2 = 2.5. Then truncates it to 2 and gives the negative integer which is -2.

3.  The modulo (%) operator also differs from C.

num6

With positive numbers (7%3 = 1) we get results similar to C. However -7%3 => 2. Two important points: The magnitude of the quotient differs and the sign differs (because in ruby the result is given the sign of the second operand). In our example, the floating point result of -7/3 is -2.33. Ruby rounds it down to -3 which is -9/3.  So how do you get -7/3?  To -9/3 we add 2/3. Thus, the answer is 2.

4.  If you want to produce results similar to C, ruby has the “remainder” method which can be used

num7

IRB (Interactive Ruby)

The best way to start learning how ruby works, is to play around in the Interactive Ruby Shell. So how do we get irb?

If you are on Windows visit RubyInstaller and you are able to download the latest version of Ruby. If you are a Mac user ruby-lang.org walks you through installing ruby.

If you are an absolute beginner, it is advised to download Ruby 1.9.3 installers. At the time of this post I am using ruby 1.9.3.

Once you have installed ruby on your machine, open your command prompt and type

C:\>ruby –version

If ruby is successfully installed you will get a response like the one below giving you the version details of your ruby installation.

C:\>ruby –version

ruby 1.9.3p392 (2013-02-22) [i386-mingw32]

To invoke irb, at the command prompt type irb and hit return

C:\>irb

irb(main):001:0>

Then you can start experimenting. For example, if you want to add two numbers in ruby, all you do is

C:\>irb

irb(main):001:0> 1 + 2

=> 3

As you can see the second line shows the value of the last expression evaluated by irb.  Of course you can experiment with various other methods like this

irb(main):001:0> 2*3

=> 6

irb(main):002:0> 2 – 3

=> -1

irb(main):003:0> 2%3

=> 2

irb(main):004:0> 2**2

=> 4

And to write that famous “Hello World” program in ruby, all you do is:

irb(main):001:0> puts ‘Hello World’

Hello World

=> nil

irb(main):002:0>

Very Neat!

I personally like irb because it’s such a great quick check tool. For example, I wanted to see how an array object would behave when I applied a method called “shuffle”. So I typed it in and irb showed me:

irb(main):005:0> p = [1, 2, 3, 4, 5, 6, 7]

=> [1, 2, 3, 4, 5, 6, 7]

irb(main):006:0> p.shuffle

=> [6, 5, 7, 3, 2, 1, 4]

irb(main):007:0>

The method did exactly what I was hoping it would and I was able to easily check it out in irb before I implemented it in my algorithm.

Foundation Ruby

Sometimes in order to make progress, it is important to take a few steps back and master the fundamentals. With rails, having a solid grounding in ruby is of paramount importance. Starting with the pre-course prep materials, Tealeaf gets you started on building that solid foundation.

 

First Step!

We’ve all heard of the cat and the curiosity thing! Well in my case thanks to my curiosity I am alive and rocking it out with my Ruby and Rails buddies! Ok, enough with the cheeky remarks.

Earlier this year, I decided to find out what Ruby on Rails was and started googling my way into web development. Very soon I began to feel that there were myriad things that had to be mastered before I could make anything happen. However, wonderful Google also showed me the path to wonderful Stack Overflow, the open source community and the Hartle tutorial. Shortly thereafter much to my amazement I deployed my very first web app!

Since then, I have made a fair amount of progress with the support of Women Who Code (SF) and RailsBridge. However, due to various time constraints, teaching myself, Ruby and Rails has been a little too slow to meet my objectives. The best way to speed up my progress appeared to be to join one of the popular classroom based bootcamps. The time and the financial constraints of such an undertaking however was not a feasible option for me. I realized that what I needed was an online bootcamp which would offer a good program and allow me to juggle within my constraints. So when a RailsBridge attendee mentioned Tealeaf Academy I decided to check it out and here I am one week into my program at Tealeaf, starting my own tech blog on Ruby and Rails.

In this blog, I will talk about anything that I find interesting on my journey towards becoming a full stack developer.