Apr 092013
 

The Ruby Programming language has two different ways by which you can represent strings in your programs:

  1. String
  2. Symbol
IMO, This stuff is the most confusing to people who are new to ruby & a friend of mine recently asked me to explain it(hence this blog post). so I am this post we will talk about the following:
  1. what is a symbol?
  2. The main differences between symbol & string?
  3. When to use symbol instead of string?
so, without wasting further time, here is the brain-dump of my explanation on symbols vs strings in ruby

What is a symbol?

A symbol is a string which is prefixed colon at starting. In other words, if you take ruby string such as “gaurish”, ‘gaurish sharma’ or “gaurish-sharma” & prefix a colon(‘:’) at te start, you get a symbol.  here is can example.

Two ways to do the essentially the same thing. Why?

Yes, you guessed it right. Strings & Symbols are essentially the thing. so why have two diffident “types” to represent string? The reason is how strings are implemented in ruby.

In Ruby, Everything is a Object including Strings

Due to SmallTalk influence, Ruby is fully object oriented language & there are no primitive types. Everything is implemented as Objects. so, when ever you try to assigned a string value to an variable like this x = “foo”, you are creating a new object in memory. Here is an small program which allocates same string to a variable 1,000 times & prints object_id of each string

As you may notice from terminal output of this program/script that each string has different object_id. ruby does creates a new object in memory every single time even thought the string is the same.

Wonder, if there is a another way?

How can I have strings which create object in memory once & all later operations refer to that previously created object with same object_id?

Glad: you asked. Enter Symbols! here is the same program with symbols.

In contrast with string, Notice how object_id is same for symbols which means its the same symbol.

What are the differences between Symbols & Strings?

  1. Symbols are immutable: Their value remains constant.
  2. Multiple uses of the same symbol have the same object ID and are the same object compared to string which will be a different object with unique object ID, everytime.
  3. You can’t call any of the String methods like #upcase, #split on Symbols.

When to use symbol instead of string?

Symbols generally have performance benefits. so will see their usage almost everywhere including getters & setters in classes, hash keys etc. here is few examples

#you will NEVER see this
class Foo
  attr_reader "name"
end

# Instead, you will ALWAYS see a symbol
class Foo
  attr_reader :name
end
#same thing but symbols are faster than strings

to use strings when:

  1. you want to use any of string methods like #upcase, #split, #downcase etc.
  2. you want to change/mutate the string

to use Symbols when:

    1. symbols can’t be changed at runtime. If you need something that absolutely, positively must remain constant
    2. Places where same string is going to be repeatably used, example hash keys are pretty good candidate for symbols. so instead of string keys, hash["key"] = value. you should  use symbols like this  hash[:key] = value 

To conclude, strings & symbols in ruby are similar but differences given above. But the main difference is that symbols are immutable & slightly more performant than strings so you should you them place where you know same string is likely to be repeated again & again.

Dec 162012
 

Recently, I have started contributing to Ruby on Rails — the popular web framework for quickly building web applications. I have just started but couple of my commits have been merged into rails core & have a pretty good idea on contributing  to rails. this guide details how you can start contributing to rails.

Step 0 – Decide what to contribute

It could be a bug or feature that you want aka starch your itch. It could a bug fix in which cause check github issue tracker for existing issues & see if you can fix anyone of them and send a Pull Request. It could be removing a warning from test. Or it would contributing documentation.

Step 1 – Fork & Change

This is rather simple but you must know how to use git – the popular distributed version control system. If you don’t then please following this guide closely & read multiple times until you understand.

  • Goto rails page on github & click the “Fork” button on the top. requires github account. so register if not already done. Its free!
  • You’ve successfully forked rails, but so far it only exists on GitHub. To be able to work on the project, you will need to clone it to your local machine.
    git clone https://github.com/your_github_username_goes_here/rails.git
    # Clones your fork of the repo into the current directory in terminal
    
  • Create a new branch
    $ git checkout -b my_branch
    
  • Create new rails app based on your fork
            $ /replace/with/path/to/your/rails/fork/railties/bin/rails new app_name_goes_here --dev
            
  • Do your changes. Now whatever changes you do, would instantly get reflected into your rails app. Once you are okay with said changed, commit them
                $ git commit -a -m "Describe your change in this message"
                # commit your changes. make sure to follow the guidance of a good commit message
           

Step 2 – Create a Pull Request

so you have made your change, tested it.Sweet! Now, its time to send your awesome changes to rails core team for review.

  • Add Upstream:
     $ git add remote git@github.com:rails/rails.git 
  • switch back to master, pull latest changes
             $ git checkout master
    	 $ git pull --rebase upstream master
    
  • Switch back your branch & Reapply your changes ontop of latest changes of the rails’ upstream master
     $ git checkout my_branch
    $ git rebase master
    
  • In the process of the rebase, it may discover conflicts. In that case it will stop and allow you to fix the conflicts. After fixing conflicts, use git add . to update the index with those contents, and then just run:
    $ git rebase --continue
    
  • Push branch to GitHub
    $ git push origin my_branch --force
    
  • Open Pull request using github’s web-interface.

Congratulation on your contribution! Now, wait for comments on the Pull request.

Step – 3

Once your Pull request is opened, most probably someone will suggest 1 or 2 changes.  hers is how to do them:

  1. switch to your feature branch
    	$ git checkout my_branch
    
  2. make changes & commit
  3. squash changes into one commit. rule is one feature == one commit
  4. force push

To close, let me welcome you the world of open source.  where code you write gets used by thousands of developers & affects lives of millions of people around the world. Its pretty amazing!

Jun 042012
 

This would serve as a quick reference for HAML.

HAML is a markup language that gets transformed into HTML. you may ask, why not write write my code in HTML, What’s wrong with HTML? And how does HAML solve does the problem?HAML_logo

Problem with HTML

HTML is verbose & becomes hard to maintain specially, if you have a large site. To see why HTML’s verbosity is issue, consider this example:

HTML

</pre>
<div id="profile">
<div class="left column">
<div id="date"><strong>4th June 2012</strong></div>
<div id="address"><em>Jaipur, India</em></div>
</div>
<div class="right column">
<div id="email"><a href="www.example.com">example.com </a></div>
<div id="bio">Rails Developer</div>
</div>
</div>
<pre>

As you may notice, there are couple of issues with html:

  1. Every starting tag has to have a ending tag
  2. The number of words & lines are more
  3. plain HTML is pain to write & read

Now, compare this to HAML which basically does the same thing but in lot more human readable form

#profile
.left.column
#date
       %strong 4th June 2012
#address
       %em Jaipur, India
.right.column
#email
       %a{:href="www.example.com"}
            example.com
#bio   Rails Developer

So in short,

Syntax Description
%tag_name produces opening & closing tags
%tag_name.class_name add a class attribute to given tag
%tag_name#id_name adds a id attribute to given tag
- runs the native code(ruby etc) but doesn’t not display result
= runs the native code(ruby etc) and display output
#body Produces div tag with id=”body” as div tag is default

For more, kindly refer to HAML official site

May 192012
 

I dislike java, by dislike I mean I do not enjoy programming in java but I still use it in situations where java feels best tool for the job, because I am technology agnostic & belive in using best tool for the job; for example writing Android Apps. And I admit I enjoy writing ruby code that much more than java that I will even write ruby from my deathbed. sounds crazy! I know!. But it’s not fanboyism, because for writing webapps — ruby & the rails stack is TEH best. In future, if something better comes along, I would switch in a heartbeat because I really believe in using best possible tools to get the job done

Now, let’s go back to the reason of this blog post. Why do I like ruby more:
well, there are lot of reasons but for me, the main reason is the philosophy behind the langauge

Ruby is designed to make programmers happy

- Matz, Creator of Ruby

To explain this, consider this ruby code:

5.times {print "My Name is Gaurish "}

so even if you do not know ruby programming or heck do not know programming at all, I am pretty sure you can know what this code is doing does just by reading aloud words by word. Why, because it reads like “5 times print my name is gaurish”.

Lets take another example, this time a bit more complex , to read a file & then print it.  here is the code to do that in Java

class FileOperations{
static void readfile(String filename) throws FileNotFoundException {
  File input = new File(filename);
  String line;
  Scanner reader = null;
  try {
    reader = new Scanner(input);
    while(reader.hasNextLine()) {
      System.out.println(reader.nextLine());
    }
  } finally { reader.close(); }
}
public static void main(String args[]){
 readfile("hello.txt");
}

}

now, compare this to ruby code which does the same thing without using classes which is mandatory in java.  Another thing is, the Java version needs to wrap the creation of the Scanner in a try block so it can be guaranteed to be closed.Now, lets compare this to ruby version of same program

def readfile(filename)
  File.open(filename, "r") do |f|
    f.each_line {|line| print line }
  end
end
readfile "hello.txt"

Because of the existence of blocks, it is possible to abstract away the need to close the File in a single location, minimizing programmer error and reducing duplication. And this is one of the reason, I like ruby more than Java. There are plenty of other reasons & maybe I will cover those in future posts, if anyone is interested, then leave a comment below

PS: I have used print, instead of puts because to highlight the readability of ruby. But if you write ruby more, you will find yourself using puts as it auto inserts a new line which has to be manually inserted when using print.

Apr 232012
 

Ruby 1.9 has a cool hash syntax which is quite similar to javascript, so the following hash

hash = {:symbol => "value"}

can be written as

hash = {symbol: "value"}

now, what if both key & values are symbols, in ruby 1.8 & before you would write

:pick => :any

but now, this could be written in short form as

pick: :any

And this both new & old syntax for hash are supported in ruby 1.9, you can use whatever syntax you are comfortable the most but it helps to know both forms of syntax specially when reading the code that other might have written. personally, I like the new one — fewer characters to type :P

 

PS: this new has syntax is applicable only if the key is a :symbol. In case when key is not a symbol. you have to still stick with old array syntax(=>)