Tuesday, August 14, 2012

Coffeescript Is Like Ruby?

Here is one reason why I find it easy to learn javascript using coffeescript. Here's the script in js. If you were NOT a programmer, would you know what this script will do?

(function() {
  var giveWork, person;

  person = {
    name: "Jim",
    job: "Programmer"
  };

  giveWork = function(person) {
    switch (person.job) {
      case "Programmer":
        return console.log("Here's your code work " + person.name);
      case "Designer":
        return console.log("Here's your design work, " + person.name);
      default:
        return console.log("Do you work here?");
    }
  };

  giveWork(person);

}).call(this);


Now here is the same script written in coffeescript. Read each line out loud and see if you can get an idea as to what this script will do...

person =
  name: "Jim"
  job: "Programmer"

giveWork = (person) ->
  switch person.job
    when "Programmer"
      console.log "Here's your code work #{person.name}"
    when "Designer" then console.log "Here's your design work, #{person.name}"
    else
      console.log "Do you work here?"

giveWork person


...and it reads like Ruby, doesn't it?

No comments:

Post a Comment