Wednesday, December 12, 2012

A quick look at the basics

Ruby. Real programming. Real deal.


Its far too early to be judging anything about this language but looking at its popularity among the core hackers of this planet, there really is no doubt that it's an awesome language. Because those hackers are not sitting idle, but are contributing to Ruby in a major way. 
Check out code school for e.g. The guys there have done an awesome job and continue to do so. In fact I am here to share what I have learned from there and would recommend it to all those who read. Buy their courses, its worth more than what you spend. They have these interactive medium for learning that helps finish courses pretty fast. I also loved the dark theme to their videos and teachings >=) 

Please read this blog simultaneously or after you have completed the course at code school.

      - yellow indicates important texts. 
      - yellow brown indicates codes.


Meet Ruby Objects


In Ruby, Numbers and Strings are Math and Text objects. They have english and symbolic methods like "reverse" and "*".
E.g. "Dimple".reverse"Gusain"*5 etc

The 'lines' method on a string object decides how the string will split up. 
For e.g. 
poem = "Bang, Bang, He shot me down. Bang, Bang, I am going down. Bang, Bang that awful sound. Bang, Bang I am going down."
poem.lines.to_a.reverse (convert it to an array and reverse it)
print poem.lines.to_a.reverse.join (… convert it back to string and print it)
  1. This is a string - "Dimple"
  2. This is a symbol - :supi
Symbols are cheaper than strings in terms of computer memory. When there is a string that occurs over and over in the program, go for a symbol. Its very easy to convert a string to symbol. Just precede it with a colon. Unlike a string, computers store the symbols only once.


Ruby Terminologies: 


  1. "lists" -  are similar to arrays. Example of a list: dimple = []
  2. "hashes" -  are similar to objects or dictionaries. The length method works on both of them. Example of a hash: supi = {}
books["<key>"] = :<value> (this is if the value is a symbol)
For e.g. books["In Love with Dimple Gusain"] = :supi , where In Love with Dimple Gusain is the key and :supi is the value
another way to instantiate an empty hash is -  dimple= Hash.new(0)


Digging into Ruby:


books.values.each { |rate| ratings[rate] += 1}
Simplification of the above code:
  • books is a hash with many values.
  • Each time, for the total length of the items in books, take each value and pipe it as an argument into the variable 'rate'. 
  • Create a new item in ratings hash with the key 'rate' and value 1 OR 
  • Increment the rating if its already there ,by 1 for each entry of the variable.
  • ratings = {} is implied

The bottom line is: **that while some methods take variables as arguments, some others take functions or blocks as arguments.** 
In the above example, the method 'each' takes the block indicated by the curly braces as the arguments and executes it in a for loop that equals the length of the hash. The beauty of this method is that it also provides each value of the hash as argument to the block for each iteration.
5.times {print "Dimple Supi"} is another example


Files and Directories in Ruby


  • Dir method holds the directories relative to the ruby executable(I guess?)
  • entires method lists all the directories and files for a supplied path. For e.g. - - Dir.entries "/"
  • read contents of a file: File.read("/Home/comics.txt") 
  • write to a file by appending: 
  • File.open("/Home/comics.txt", "a") do |f| 
  • f << "supi and dimple: http://supianddimple.com/"
  • end
  • Copy file contents to the specified path, if no such file then create one:FileUtils.cp(/comics.txt', 'Home/comics.txt')
  • modified time for a file: File.mtime("/Home/comics.txt")
  • 'foreach' method on file returns the contents of the file in a line for the total number of lines in the file.


Method definition in Ruby:


  • starts with 'def' keyword and ends with 'end' keyword. 
  • For e.g. 
def load_comics(path) 
comics = {}
File.foreach(path) do |line|
name, url = line.split(": ") // splits the string to array and assigns the first element to first variable, second to second, etc
comics[name] = url.strip // strips any associated whitespace 
end
comics
end

Use the 'require' method to load libraries. for e.g. require "dimplegusain"


A class in Ruby:


  • class DimpleGusain
  • You can add attributes to the class as follows: attr_accessor
  • You can also add methods later with the def statements. the initialize method is called every time the new keyword is used to instantiate an object from the class
  • We always use @<attribute> (without the colons of course) for accessing the attribute within the class but we always use the accessor method outside the class. supi.time, supi.title etc
  • by the by, supi = DimpleGusain.new was implied


Methods on an array in Ruby:


  • 'sort_by' method on an array takes in arguments as blocks so that it can sort the array based on that.
  • 'map' method replaces the array elements with whatever the block returns for each iteration . For e.g. supi.map {"Dimple Gusain} Every entry in supi is now replaced with Dimple Gusain 


More posts on beginner perspective follows soon after I am done with rails ;) 
\,,/