Tuesday, September 20, 2011

The Great Ruby, Not Another Scripting Language

Armed with some experiences in dynamic programming language from Lisp, Perl, to (L/U)nix shell scripting languages, to high-level compiled languages like C, C#, and C++ to intermediate language like Java, I could not help asking "what the heck is Ruby?" when the world rumbles the word R-u-b-y.  


With that curiosity lingering in mind, you figure out what I would do next?  Yes, I google-d and I amazon-ed for anything Ruby and sure enough, within 2 hours, The Ruby is sitting quietly in my lap waiting for me to explore.


Then after 30 minutes playing with irb managing to print out the great shameful "Hello World" example, I paused.  What the h***?  What is new that I didn't see before?  Yes, Ruby is a objected oriented language much like Python/Java that I could instantiate an object with Object.new; Yes, like Lisp  that supports lambda or block, I could surely define a block dynamically; and sure, Ruby syntax looks like the best mix of all languages I know; and yet, to Ruby's credit, I no longer have to deal with the hateful Perl's syntax.  


That's very nice but that still does not convince me anything?  Did I miss anything here?  It must be just those investors who have so much Franklin bills to throw around to invest into these "marketing-hyped" IT.  But before I hung up on that thought and would trash my ThinkPad T61 laptop with anger, I took a timeout, a practice I learned at work and so thanks to the "Anger Management" course, I took a glass of 500-ml fresh water, munging a full fresh apple and with that much vitamins, I smartly google-d for the biography of Ruby-inventor Matz and his own introduction of the language, then hit the highly-reviewed Ruby Metaprogramming book.  Soon enough, I meant, until the next night (I really meant "night" after my kids went to bed), I then started to realize that Ruby is surely a better language in many ways but what makes it powerful language is the ecosystem built around it; among which Rails, the web application framework, deserves most of the credit.  


In the incoming articles, I hope I will shed some lights on key benefits of Ruby that makes it so popular and de-facto standard language for new web-based software applications.  So, don't be surprised if you're looking for a job and recruiters keep asking for Ruby and RoR experiences.  In which case, I would highly recommend that you get into it and whether you will get a Ruby job or not, your time will be worth it.

My hobby, photography


For my hobby, photography, let me start by saying that I'm still a novice shooter who started out to shoot landscape but since I don't travel much so landscape becomes rare thing to shoot.  Things have changed for me in a good way after I met a local shooter, Huy Phamwho also started out 4 years ago and has influenced me in a big way (I will come back to this more later) and we have become photography friends since.  That's when I began to learn how to shoot portrait and more importantly, environmental portrait.  With my kids and families, I now have no more excuse of saying that I don't have any "people" to shoot and that by photographing my kids, I have a chance to work and refine my techniques.


What gears do I own, you ask?  Sure, I'm a Canon shooter for a reason.  Canon offers a lot more choices of lenses and cameras at an affordable prices than its counterpart Nikon, so that's how I chose Canon.


My gears: 5dII, 17-40mm f4, 70-200mm f2.8 IS.


Over the time, these are the successful and well-known photographers I have learned from and have followed them for a long time. The list will continue to be updated based on what style I like to shoot and me most.
  • Manny Librodo, landscape of emotion, who I learned to shoot my first environment portrait using natural light.
  • Neil Van Neikerk, wedding photographer in NJ, known for his best-selling off-camera Flash and on-camera flash book.
  • Steven Eastwood, fashion photographer in NY.
  • David Hobby, the king of off-camera flash with his famous Strobist blog.  If you're new with flash and want to know how to start, you should not miss this blog.
  • David Ziser, well-known wedding photographer, who is very meticulous at his loop lighting pattern on his portrait shots.  He is a fan of extreme wide-angle and fish-eye lenses and his photos will show you why so.
  • Huy Pham, a friend and my motivator.  You will definitely open your eyes to see his beautiful and breath-taking crafts.
Last but  not least, feel free to browse my Phi Tran @ PBase web site here for my photography works.


Below is my little 2-year-old girl, Sophie 'Cat Lynh'





And my beloved 5-year-old son, Ryan 'Huy'



Monday, September 19, 2011

Ruby Symbol Explained

Symbol is a bit confusing for Ruby learner to comprehend so if you happen to be one of us, don't be too worry as you will find out it's not as bad as it first looks.  


So, what is a symbol? According Ruby-doc,
Symbol objects represent names and some strings inside the Ruby interpreter. They are generated using the :name and :"string" literals syntax, and by the various to_sym methods. The same Symbol object will be created for a given name or string for the duration of a program‘s execution, regardless of the context or meaning of that name. Thus if Fred is a constant in one context, a method in another, and a class in a third, the symbol :Fred will be the same object in all three contexts.
What that means are:
  • If you prefix a string or an legal Ruby name/identifier with a colon, it becomes a symbol
    • x = :"Matt" # x.class is a Symbol
    • x.to_s() "Matt"
    • y = :userId # y.class is a Symbol
    • y.to_s() # "userId"
  • A symbol is an instance of Symbol class.  If you runs Symbol.public_methods(false), irb will return 3 methods: ["superclass", "allocate", "all_symbols"].  all_symbols() method returns a table of symbols currently bound by runtime Ruby.
  • Symbols are not strings because Symbol and String are 2 different classes.  You cannot therefore do the following:
    • Assign :user = "Sam"  # syntax error, unexpected '=', expecting $end
      • The correct way to assign a symbol is user = :"Sam"
    • Invoke String's method :user.size() # NoMethodError: undefined method `size' for user:Symbol
      • Correct way to get size of User symbol's value is :user.to_s().size()
  • Symbol's value, a string, is obtained via via Symbol#to_s() or Symbol#id2name() methods.  Vice versa, a string can be converted to Symbol via String#to_sym() or String#intern().
  • Symbol is immutable so unlike String, you cannot modify a string once assigned.  
    • user.to_s()[0] = "K" # changing first character of 'Sam' will not affect user.  Afterward, user.to_s() is still "Matt"
    • Bonus: you can make a string/array object immutable via freeze() method.  Vice versa, unfreeze() will allow string/array object to be editable.
Fine, you start to get impatient.  Then tell me why and where you want to use symbol?
  1. Symbol as a key in Hash's key instead of string.  Instead of having to refer to "id" string whenever rec["id"] is called, a good engineer would at least define a constant like static const String ID = "id in Java and always refer to rec[ID] instead.  Ruby symbol does exactly that.
    • rec = { id => :"101"; name => :"Matt Burnes"; email => :"mburnes@mclub.org" } # rec.class returns Hash
    • p rec[:id] # "101" 
  2. Save memory when replace a large number of identical strings.  Since symbol id is a reference to a same identical "id", you reuse same memory for identical "id" every time "id" string is referred.  I wish Ruby could be as smart as Java where it figures out if same literal string "id" is instantiated, any time it encounters same string, it will just reference it. 
    • id.object_id   # returns 303408
    • "id".object_id 23700936
    • "id".object_id 23689692 (new object)
    • "id".object_id 23485564 (new object)
    • id.object_id   # still returns 303408
Conclusion
  • Symbol is immutable.
  • Symbol is not a string.
  • Symbol is favored over String when same string is referenced repeatedly to save memory.