SlideShare a Scribd company logo
1 of 104
Download to read offline
COFFEESCRIPT
   A Rubyist’s Love Affair

     @markbates
ALOHA!
Cats
Cats
CoffeeScript for the Rubyist
Distributed
Programming
    with
    Ruby
     Addison-Wesley
          2009


http://books.markbates.com
Programming
      in
 CoffeeScript
      Addison-Wesley
           2012


 http://books.markbates.com
A (BRIEF) HISTORY LESSON
CoffeeScript for the Rubyist
“
I need to come up with a scripting language
for web browsers.


    I know! I'll make it cool and Lispy!      ”
               Dramatic Re-enactment (1995)
CoffeeScript for the Rubyist
“   Yeah, So... Java is getting really popular.
    So we're going to need you to rewrite your
    language into something a bit more Java-
    esque and name it something like JavaScript.
 
    Yeah, and we're going to need it in a week.


    Thanks, that'd be great.    ”
                Dramatic Re-enactment (1995)
var MyApp.Models.Product = Backbone.Model.extend({

  isLiked: function() {
     var _ref;
     return ! ((_ref = this.like()) != null ? _ref.isNew() : void 0);
  };

  like: function() {
     return new MyApp.Models.Like(this.get("like"));
  };

  image: function(size) {
     var img;
     if (size == null) {
       size = "full";
     }
     if (this.get("image") != null) {
       img = this.get("image")[size];
     }
     if (img == null) {
       img = "/images/fallback/product_" + size + "_default.png";
     }
     return img;
  };

});
FAST FORWARD
    About 15 Years
CoffeeScript for the Rubyist
var MyApp.Models.Product = Backbone.Model.extend({

  isLiked: function() {
     var _ref;
     return ! ((_ref = this.like()) != null ? _ref.isNew() : void 0);
  };

  like: function() {
     return new MyApp.Models.Like(this.get("like"));
  };

  image: function(size) {
     var img;
     if (size == null) {
       size = "full";
     }
     if (this.get("image") != null) {
       img = this.get("image")[size];
     }
     if (img == null) {
       img = "/images/fallback/product_" + size + "_default.png";
     }
     return img;
  };

});
class MyApp.Models.Product extends Backbone.Model

  isLiked: ->
    !@like()?.isNew()

  like: ->
    new MyApp.Models.Like(@get("like"))

  image: (size = "full") ->
    if @get("image")?
      img = @get("image")[size]
    unless img?
      img = "/images/fallback/product_#{size}_default.png"
    return img
WHAT IS COFFEESCRIPT?
What is CoffeeScript?
What is CoffeeScript?

“A little language that compiles into JavaScript.”
What is CoffeeScript?

“A little language that compiles into JavaScript.”

Easily integrates with your current JavaScript
What is CoffeeScript?

“A little language that compiles into JavaScript.”

Easily integrates with your current JavaScript

Easier to read, write, maintain, refactor, etc...
What is CoffeeScript?

“A little language that compiles into JavaScript.”

Easily integrates with your current JavaScript

Easier to read, write, maintain, refactor, etc...

A Hybrid of Ruby and Python.
What is CoffeeScript?

“A little language that compiles into JavaScript.”

Easily integrates with your current JavaScript

Easier to read, write, maintain, refactor, etc...

A Hybrid of Ruby and Python.

Helpful.
What CoffeeScript Is Not?


Not Magic!

Limited by what JavaScript can already do
“
I’m happy writing JavaScript.

I don’t need to learn another language.   ”
FINE WITH ME
BUT...
ANOTHER (BRIEF) HISTORY
       LESSON
.MODEL SMALL                           DISP:
                                               MOV BL,VAL1
.STACK 64                                      ADD BL,VAL2

.DATA                                          MOV   AH,00H
        VAL1       DB    01H                   MOV   AL,BL
        VAL2       DB    01H                   MOV   LP,CL
        LP         DB    00H                   MOV   CL,10
        V1         DB    00H                   DIV   CL
        V2         DB    00H                   MOV   CL,LP
        NL         DB    0DH,0AH,'$'
                                               MOV V1,AL
.CODE                                          MOV V2,AH

MAIN PROC                                      MOV   DL,V1
        MOV AX,@DATA                           ADD   DL,30H
        MOV DS,AX                              MOV   AH,02H
                                               INT   21H
        MOV    AH,01H
        INT    21H                             MOV   DL,V2
        MOV    CL,AL                           ADD   DL,30H
        SUB    CL,30H                          MOV   AH,02H
        SUB    CL,2                            INT   21H

        MOV    AH,02H                          MOV DL,VAL2
        MOV    DL,VAL1                         MOV VAL1,DL
        ADD    DL,30H                          MOV VAL2,BL
        INT    21H
                                               MOV AH,09H
        MOV AH,09H                             LEA DX,NL
        LEA DX,NL                              INT 21H
        INT 21H
                                               LOOP DISP
        MOV    AH,02H
        MOV    DL,VAL2                         MOV AH,4CH
        ADD    DL,30H                          INT 21H
        INT    21H
                                       MAIN ENDP
        MOV AH,09H                     END MAIN
        LEA DX,NL
        INT 21H
.MODEL SMALL                           DISP:

.STACK 64
                                               MOV BL,VAL1
                                               ADD BL,VAL2    Assembly
.DATA                                          MOV   AH,00H
        VAL1       DB    01H                   MOV   AL,BL
        VAL2       DB    01H                   MOV   LP,CL
        LP         DB    00H                   MOV   CL,10
        V1         DB    00H                   DIV   CL
        V2         DB    00H                   MOV   CL,LP
        NL         DB    0DH,0AH,'$'
                                               MOV V1,AL
.CODE                                          MOV V2,AH

MAIN PROC                                      MOV   DL,V1
        MOV AX,@DATA                           ADD   DL,30H
        MOV DS,AX                              MOV   AH,02H
                                               INT   21H
        MOV    AH,01H
        INT    21H                             MOV   DL,V2
        MOV    CL,AL                           ADD   DL,30H
        SUB    CL,30H                          MOV   AH,02H
        SUB    CL,2                            INT   21H

        MOV    AH,02H                          MOV DL,VAL2
        MOV    DL,VAL1                         MOV VAL1,DL
        ADD    DL,30H                          MOV VAL2,BL
        INT    21H
                                               MOV AH,09H
        MOV AH,09H                             LEA DX,NL
        LEA DX,NL                              INT 21H
        INT 21H
                                               LOOP DISP
        MOV    AH,02H
        MOV    DL,VAL2                         MOV AH,4CH
        ADD    DL,30H                          INT 21H
        INT    21H
                                       MAIN ENDP
        MOV AH,09H                     END MAIN
        LEA DX,NL
        INT 21H
#include <stdio.h>            C

int fibonacci()
{
  int n = 100;
  int a = 0;
  int b = 1;
  int sum;
  int i;

    for (i = 0; i < n; i++)
    {
      printf("%dn", a);
      sum = a + b;
      a = b;
      b = sum;
    }
    return 0;
}
public static void fibonacci() {    Java
  int n = 100;
  int a = 0;
  int b = 1;

    for (int i = 0; i < n; i++) {
      System.out.println(a);
      a = a + b;
      b = a - b;
    }
}
def fibonacci           Ruby
  a = 0
  b = 1

  100.times do
    printf("%dn", a)
    a, b = b, a + b
  end

end
“
I can write an app just as well in Java

as I can in Ruby, but damn it if Ruby


isn’t nicer to read and write!   ”
SAME GOES FOR
COFFEESCRIPT
SYNTAX
$(function() {                             $ ->
                                             success = (data) ->
  success = function(data) {                    if data.errors?
     if (data.errors != null) {                   alert "There was an error!"
       alert("There was an error!");            else
     } else {                                     $("#content").text(data.message)
       $("#content").text(data.message);
     }                                       $.get('/users', success, 'json')
  };

  $.get('/users', success, 'json');

});          JavaScript                                CoffeeScript
Syntax Rules

No semi-colons (ever!)

No curly braces*

No ‘function’ keyword

Relaxed parentheses

Whitespace significant formatting
Parentheses Rules
# Not required without arguments:
noArg1 = ->
  # do something

# Not required without arguments:
noArg2 = () ->
  # do something
                                # Required without arguments:
# Required with Arguments:      noArg1()
withArg = (arg) ->              noArg2()
  # do something
                               # Not required with
                               arguments:
                               withArg("bar")
                               withArg "bar"
Parentheses Rules
# Bad:
$ "#some_id" .text()
# $("#some_id".text());

# Good:
$("#some_id").text()
# $("#some_id").text();
Whitespace
Whitespace
$(function() {
success = function(data) {
if (data.errors != null) {
alert("There was an error!");
} else {
$("#content").text(data.message);
}
};
$.get('/users', success, 'json');
});
Whitespace
$(function() {                      def fibonacci
success = function(data) {          a = 0
if (data.errors != null) {          b = 1
alert("There was an error!");       100.times do
} else {                            printf("%dn", a)
$("#content").text(data.message);   a, b = b, a + b
}                                   end
};                                  end
$.get('/users', success, 'json');
});
Whitespace
$(function() {                             def fibonacci
                                             a = 0
  success = function(data) {                 b = 1
     if (data.errors != null) {
       alert("There was an error!");         100.times do
     } else {                                  printf("%dn", a)
       $("#content").text(data.message);       a, b = b, a + b
     }                                       end
  };
                                           end
  $.get('/users', success, 'json');

});
Whitespace
$ ->
  success = (data) ->
     if data.errors?
       alert "There was an error!"
     else
       $("#content").text(data.message)

  $.get('/users', success, 'json')
RUBYSCRIPT?
Conditionals
if true                    doSomething() if true
  doSomething()
                           doSomething() unless true
unless true
  doSomething()
                   if true
                     doSomething()
                   else
                     doSomethingElse()
Objects/Hashes
someObject = {conf: "AlohaRubyConf", talk: "CoffeeScript"}

someObject =
  conf: "AlohaRubyConf"
  talk: "CoffeeScript"

someFunction(conf: "AlohaRubyConf", talk: "CoffeeScript")
Objects/Hashes
var someObject;

someObject = {
   conf: "AlohaRubyConf",
   talk: "CoffeeScript"
};

someObject = {
   conf: "AlohaRubyConf",
   talk: "CoffeeScript"
};

someFunction({
  conf: "AlohaRubyConf",
  talk: "CoffeeScript"
});
String Interpolation
name = "AlohaRubyConf 2012"

console.log "Hello #{name}"
# Hello AlohaRubyConf 2012

console.log 'Hello #{name}'
# Hello #{name}
String Interpolation
name = "AlohaRubyConf 2012"   var name;

console.log "Hello #{name}"   name = "AlohaRubyConf 2012";
# Hello AlohaRubyConf 2012
                              console.log("Hello " + name);
console.log 'Hello #{name}'
# Hello #{name}               console.log('Hello #{name}');
Heredocs
html = """
  <div class="comment" id="tweet-#{tweet.id_str}">
    <hr>
    <div class='tweet'>
      <span class="imgr"><img
src="#{tweet.profile_image_url}"></span>
      <span class="txtr">
         <h5><a href="http://twitter.com/#{tweet.from_user}"
target="_blank">@#{tweet.from_user}</a></h5>
         <p>#{tweet.text}</p>
         <p class="comment-posted-on">#{tweet.created_at}</p>
      </span>
    </div>
  </div>
"""
Heredocs
var html;

html = "<div class="comment" id="tweet-" + tweet.id_str
+ "">n <hr>n <div class='tweet'>n      <span class=
"imgr"><img src="" + tweet.profile_image_url + ""></
span>n    <span class="txtr">n      <h5><a href=
"http://twitter.com/" + tweet.from_user + "" target=
"_blank">@" + tweet.from_user + "</a></h5>n       <p>" +
tweet.text + "</p>n      <p class="comment-posted-on">"
+ tweet.created_at + "</p>n    </span>n </div>n</div>";
Functions
p = (name) ->
  console.log "Hello #{name}"

p('AlohaRubyConf 2012')
Functions
var p;

p = function(name) {
   return console.log("Hello " + name);
};

p('AlohaRubyConf 2012');
Functions
p = (name)->
  console.log "Hello #{name}"

p('AlohaRubyConf 2012')
Functions
p = (name)->
  console.log "Hello #{name}"   CoffeeScript
p('AlohaRubyConf 2012')
Functions
p = (name)->
  console.log "Hello #{name}"   CoffeeScript
p('AlohaRubyConf 2012')




p = ->(name) {
  puts "Hello #{name}"
}
                                Ruby 1.9
p.call('AlohaRubyConf 2012')
Loops & Comprehensions
for someName in someArray
  console.log someName

for key, value of someObject
  console.log "#{key}: #{value}"
Loops & Comprehensions
var key, someName, value, _i, _len;

for (_i = 0, _len = someArray.length; _i < _len; _i++) {
  someName = someArray[_i];
  console.log(someName);
}

for (key in someObject) {
  value = someObject[key];
  console.log("" + key + ": " + value);
}
Loops & Comprehensions
numbers = [1..5]

console.log number for number in numbers
Loops & Comprehensions
var number, numbers, _i, _len;

numbers = [1, 2, 3, 4, 5];

for (_i = 0, _len = numbers.length; _i < _len; _i++) {
  number = numbers[_i];
  console.log(number);
}
Loops & Comprehensions
numbers = [1..5]

console.log number for number in numbers when number <= 3
Loops & Comprehensions
var number, numbers, _i, _len;

numbers = [1, 2, 3, 4, 5];

for (_i = 0, _len = numbers.length; _i < _len; _i++) {
  number = numbers[_i];
  if (number <= 3) {
    console.log(number);
  }
}
Loops & Comprehensions
numbers = [1, 2, 3, 4, 5]

low_numbers = (number * 2 for number in numbers when number <= 3)

console.log low_numbers # [ 2, 4, 6 ]
Loops & Comprehensions
var low_numbers, number, numbers;

numbers = [1, 2, 3, 4, 5];

low_numbers = (function() {
  var _i, _len, _results;
  _results = [];
  for (_i = 0, _len = numbers.length; _i < _len; _i++) {
    number = numbers[_i];
    if (number <= 3) {
      _results.push(number * 2);
    }
  }
  return _results;
})();

console.log(low_numbers);
Classes
class Employee

emp = new Employee()
emp.firstName = "Mark"
Classes
var Employee, emp;

Employee = (function() {

  Employee.name = 'Employee';

  function Employee() {}

  return Employee;

})();

emp = new Employee();

emp.firstName = "Mark";
Classes
class Employee

  constructor: (@options = {}) ->

  salary: ->
    @options.salary ?= "$250,000"

emp = new Employee()
console.log emp.salary() # "$250,000"

emp = new Employee(salary: "$100,000")
console.log emp.salary() # "$100,000"
Classes
var Employee, emp;

Employee = (function() {

  Employee.name = 'Employee';

  function Employee(options) {
    this.options = options != null ? options : {};
  }

  Employee.prototype.salary = function() {
     var _base, _ref;
     return (_ref = (_base = this.options).salary) != null ? _ref : _base.salary = "$250,000";
  };

  return Employee;

})();

emp = new Employee();

console.log(emp.salary());

emp = new Employee({
  salary: "$100,000"
});

console.log(emp.salary());
Extending Classes

class Manager extends Employee

  salary: ->
    "#{super} w/ $10k Bonus"

manager = new Manager()
console.log manager.salary() # "$250,000 w/ $10k Bonus"
Extending Classes
var Manager, manager,
  __hasProp = {}.hasOwnProperty,
  __extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; }
function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor; child.__super__ =
parent.prototype; return child; };

Manager = (function(_super) {

  __extends(Manager, _super);

  Manager.name = 'Manager';

  function Manager() {
    var _base;
    Manager.__super__.constructor.apply(this, arguments);
  }

  Manager.prototype.salary = function() {
     return "" + Manager.__super__.salary.apply(this, arguments) + " w/ $10k Bonus";
  };

  return Manager;

})(Employee);

manager = new Manager();

console.log(manager.salary());
Bound Functions
class User

  constructor: (@name) ->

  sayHi: ->
    console.log "Hello #{@name}"

bob = new User('bob')
mary = new User('mary')

log = (callback)->
  console.log "about to execute callback..."
  callback()
  console.log "...executed callback"

log(bob.sayHi)
log(mary.sayHi)
Bound Functions
about to execute callback...
Hello undefined
...executed callback
about to execute callback...
Hello undefined
...executed callback
Bound Functions
class User

  constructor: (@name) ->

  sayHi: ->
    console.log "Hello #{@name}"

bob = new User('bob')
mary = new User('mary')

log = (callback)->
  console.log "about to execute callback..."
  callback()
  console.log "...executed callback"

log(bob.sayHi)
log(mary.sayHi)
Bound Functions
class User

  constructor: (@name) ->

  sayHi: ->
    console.log "Hello #{@name}"

bob = new User('bob')
mary = new User('mary')

log = (callback)->
  console.log "about to execute callback..."
  callback()
  console.log "...executed callback"

log(bob.sayHi)
log(mary.sayHi)
Bound Functions
class User

  constructor: (@name) ->

  sayHi: =>
    console.log "Hello #{@name}"

bob = new User('bob')
mary = new User('mary')

log = (callback)->
  console.log "about to execute callback..."
  callback()
  console.log "...executed callback"

log(bob.sayHi)
log(mary.sayHi)
Bound Functions
about to execute callback...
Hello bob
...executed callback
about to execute callback...
Hello mary
...executed callback
Bound Functions
class User

  constructor: (@name) ->

  sayHi: =>
    console.log "Hello #{@name}"
Bound Functions
var User,
  __bind = function(fn, me){ return function(){ return fn.apply(me,
arguments); }; };

User = (function() {

  User.name = 'User';

  function User(name) {
    this.name = name;
    this.sayHi = __bind(this.sayHi, this);
  }

  User.prototype.sayHi = function() {
     return console.log("Hello " + this.name);
  };

  return User;

})();
FINALLY
One of my favorite features
Existential Operator
if foo?
  console.log "foo"
Existential Operator

if (typeof foo !== "undefined" && foo !== null) {
  console.log("foo");
}
BUT WAIT! THERE’S MORE!
Existential Operator
console?.log "foo"
Existential Operator
console?.log "foo"




if (typeof console !== "undefined" && console !== null) {
  console.log("foo");
}
Existential Operator
if currentUser?.firstName?
  console.log currentUser.firstName
Existential Operator
if currentUser?.firstName?
  console.log currentUser.firstName




if ((typeof currentUser !== "undefined" && currentUser !==
null ? currentUser.firstName : void 0) != null) {
  console.log(currentUser.firstName);
}
FINALLY
The Raven
The Raven
Once upon a mignight dreary while I pondered, weak and weary,
Over many quaint and curious volume of forgotten lore -
While I nodded, nearly napping, suddenly there came a tapping,
As of some one gently rapping, rapping at my chamber door
"'Tis some visiter". I muttered, "tapping at my chamber door" -
"only this and nothing more."

Ah distinctly I remember it was in the bleak December;
And each separate dying ember wrought its ghost upon the floor.
Eagerly I wished the morrow - vainly I had sought to borrow,
From my books surcease of sorrow - sorrow For the lost Lenore -
For the rare and radiant maiden whom the angels name Lenore -
Nameless here For evermore
The Raven
var __indexOf = [].indexOf || function(item) { for (var i = 0, l = this.length;
i < l; i++) { if (i in this && this[i] === item) return i; } return -1; };

while (I(pondered, weak && weary, Over(many(quaint && curious(volume in
forgotten(lore - While(I(nodded, nearly(napping, suddenly(there(came(a(tapping,
As in some(one(gently(rapping, rapping(at(my(chamber(door)))))))))))))))))))) {
  Once(upon(a(mignight(dreary))));
}

"'Tis some visiter".I(muttered, "tapping at my chamber door" - "only this and
nothing more.");

Ah(distinctly(I(remember(it(__indexOf.call(the(bleak(December)), was) >= 0)))));

And(each(separate(dying(ember(wrought(its(ghost(upon(the(floor.Eagerly(I(wished(
the(morrow - vainly(I(had(sought(to(borrow, From(my(books(surcease in sorrow -
sorrow(For(the(lost(Lenore - For(the(rare &&
radiant(maiden(whom(the(angels(name(Lenore -
Nameless(here(For(evermore)))))))))))))))))))))))))))))))))))));
CELEBRITY ENDORSEMENTS
Matt Aimonetti
Matt Aimonetti


“You should go to Mark’s Talk.”
Matt Aimonetti


“You should go to Mark’s Talk.”
“Buy... his... book. It’s... Great.”
Corey Haines
Corey Haines

“When I’m not engaged in auto-
  erotic asphyxiation I write
 CoffeeScript, you should too!”
Konstantin Haase
Konstantin Haase

   “I’m not negative, I’m just
German, but I’m definitely positive
      about CoffeeScript!”
What Didn’t I Cover?
Default Arguments         Operators

Ranges                    The `do` keyword

Splatted Arguments        Plenty more!

Scoping

Security

Strict Mode

Fixes common ‘mistakes’
Mahalo!
Mahalo!
myName = "Mark Bates"

you.should buyBook("Programming in CoffeeScript")
 .at("http://books.markbates.com")

you.should followMe(@markbates)

More Related Content

Similar to CoffeeScript for the Rubyist

8051 experiments1
8051 experiments18051 experiments1
8051 experiments1tt_aljobory
 
Maicrocontroller lab basic experiments
Maicrocontroller lab basic experimentsMaicrocontroller lab basic experiments
Maicrocontroller lab basic experimentsNoor Tahasildar
 
Maicrocontroller lab basic experiments
Maicrocontroller lab basic experimentsMaicrocontroller lab basic experiments
Maicrocontroller lab basic experimentsnoorahamed tahasildar
 
Maicrocontroller lab basic experiments
Maicrocontroller lab basic experiments Maicrocontroller lab basic experiments
Maicrocontroller lab basic experiments noorahamed tahasildar
 
Micro Controller lab basic experiments (1)
Micro Controller lab basic experiments (1)Micro Controller lab basic experiments (1)
Micro Controller lab basic experiments (1)Noor Tahasildar
 
פרק 6 המחסנית ותת תכניות
פרק 6 המחסנית ותת תכניותפרק 6 המחסנית ותת תכניות
פרק 6 המחסנית ותת תכניותlizliziz
 
פרק 6 המחסנית ותת תכניות
פרק 6 המחסנית ותת תכניותפרק 6 המחסנית ותת תכניות
פרק 6 המחסנית ותת תכניותlizliziz
 
פרק 6 המחסנית ותת תכניות
פרק 6 המחסנית ותת תכניותפרק 6 המחסנית ותת תכניות
פרק 6 המחסנית ותת תכניותlizliziz
 
Microcontroller 8051 soft
Microcontroller 8051  softMicrocontroller 8051  soft
Microcontroller 8051 softbaluusa8
 
Assembly Language Voltage Divider Bias Program 8086
Assembly Language Voltage Divider Bias Program 8086Assembly Language Voltage Divider Bias Program 8086
Assembly Language Voltage Divider Bias Program 8086Sami Ullah
 
Programs using Microcontrollers.ppt
Programs using Microcontrollers.pptPrograms using Microcontrollers.ppt
Programs using Microcontrollers.pptSasiBhushan22
 
Buy Embedded Systems Projects Online,Buy B tech Projects Online
Buy Embedded Systems Projects Online,Buy B tech Projects OnlineBuy Embedded Systems Projects Online,Buy B tech Projects Online
Buy Embedded Systems Projects Online,Buy B tech Projects OnlineTechnogroovy
 
Microcontroller 8051- soft.ppt
Microcontroller 8051- soft.pptMicrocontroller 8051- soft.ppt
Microcontroller 8051- soft.pptsteffydean
 
Instalación de emu8086 y compilados
Instalación de emu8086 y compiladosInstalación de emu8086 y compilados
Instalación de emu8086 y compiladosDiego Erazo
 
Whats up at the virtualization/emulation front?
Whats up at the virtualization/emulation front?Whats up at the virtualization/emulation front?
Whats up at the virtualization/emulation front?chhorn
 
Lenguaje ensamblador EMU8086
Lenguaje ensamblador EMU8086Lenguaje ensamblador EMU8086
Lenguaje ensamblador EMU8086Santy Bolo
 
Emulador de ensamblador emu8086
Emulador de ensamblador emu8086Emulador de ensamblador emu8086
Emulador de ensamblador emu8086Marco Muñoz
 

Similar to CoffeeScript for the Rubyist (17)

8051 experiments1
8051 experiments18051 experiments1
8051 experiments1
 
Maicrocontroller lab basic experiments
Maicrocontroller lab basic experimentsMaicrocontroller lab basic experiments
Maicrocontroller lab basic experiments
 
Maicrocontroller lab basic experiments
Maicrocontroller lab basic experimentsMaicrocontroller lab basic experiments
Maicrocontroller lab basic experiments
 
Maicrocontroller lab basic experiments
Maicrocontroller lab basic experiments Maicrocontroller lab basic experiments
Maicrocontroller lab basic experiments
 
Micro Controller lab basic experiments (1)
Micro Controller lab basic experiments (1)Micro Controller lab basic experiments (1)
Micro Controller lab basic experiments (1)
 
פרק 6 המחסנית ותת תכניות
פרק 6 המחסנית ותת תכניותפרק 6 המחסנית ותת תכניות
פרק 6 המחסנית ותת תכניות
 
פרק 6 המחסנית ותת תכניות
פרק 6 המחסנית ותת תכניותפרק 6 המחסנית ותת תכניות
פרק 6 המחסנית ותת תכניות
 
פרק 6 המחסנית ותת תכניות
פרק 6 המחסנית ותת תכניותפרק 6 המחסנית ותת תכניות
פרק 6 המחסנית ותת תכניות
 
Microcontroller 8051 soft
Microcontroller 8051  softMicrocontroller 8051  soft
Microcontroller 8051 soft
 
Assembly Language Voltage Divider Bias Program 8086
Assembly Language Voltage Divider Bias Program 8086Assembly Language Voltage Divider Bias Program 8086
Assembly Language Voltage Divider Bias Program 8086
 
Programs using Microcontrollers.ppt
Programs using Microcontrollers.pptPrograms using Microcontrollers.ppt
Programs using Microcontrollers.ppt
 
Buy Embedded Systems Projects Online,Buy B tech Projects Online
Buy Embedded Systems Projects Online,Buy B tech Projects OnlineBuy Embedded Systems Projects Online,Buy B tech Projects Online
Buy Embedded Systems Projects Online,Buy B tech Projects Online
 
Microcontroller 8051- soft.ppt
Microcontroller 8051- soft.pptMicrocontroller 8051- soft.ppt
Microcontroller 8051- soft.ppt
 
Instalación de emu8086 y compilados
Instalación de emu8086 y compiladosInstalación de emu8086 y compilados
Instalación de emu8086 y compilados
 
Whats up at the virtualization/emulation front?
Whats up at the virtualization/emulation front?Whats up at the virtualization/emulation front?
Whats up at the virtualization/emulation front?
 
Lenguaje ensamblador EMU8086
Lenguaje ensamblador EMU8086Lenguaje ensamblador EMU8086
Lenguaje ensamblador EMU8086
 
Emulador de ensamblador emu8086
Emulador de ensamblador emu8086Emulador de ensamblador emu8086
Emulador de ensamblador emu8086
 

More from Mark

Mangling Ruby with TracePoint
Mangling Ruby with TracePointMangling Ruby with TracePoint
Mangling Ruby with TracePointMark
 
AngularJS vs. Ember.js vs. Backbone.js
AngularJS vs. Ember.js vs. Backbone.jsAngularJS vs. Ember.js vs. Backbone.js
AngularJS vs. Ember.js vs. Backbone.jsMark
 
A Big Look at MiniTest
A Big Look at MiniTestA Big Look at MiniTest
A Big Look at MiniTestMark
 
A Big Look at MiniTest
A Big Look at MiniTestA Big Look at MiniTest
A Big Look at MiniTestMark
 
GET /better
GET /betterGET /better
GET /betterMark
 
CoffeeScript
CoffeeScriptCoffeeScript
CoffeeScriptMark
 
Testing Your JavaScript & CoffeeScript
Testing Your JavaScript & CoffeeScriptTesting Your JavaScript & CoffeeScript
Testing Your JavaScript & CoffeeScriptMark
 
Building an API in Rails without Realizing It
Building an API in Rails without Realizing ItBuilding an API in Rails without Realizing It
Building an API in Rails without Realizing ItMark
 
5 Favorite Gems (Lightning Talk(
5 Favorite Gems (Lightning Talk(5 Favorite Gems (Lightning Talk(
5 Favorite Gems (Lightning Talk(Mark
 
RubyMotion
RubyMotionRubyMotion
RubyMotionMark
 
Testing JavaScript/CoffeeScript with Mocha and Chai
Testing JavaScript/CoffeeScript with Mocha and ChaiTesting JavaScript/CoffeeScript with Mocha and Chai
Testing JavaScript/CoffeeScript with Mocha and ChaiMark
 
Testing Rich Client Side Apps with Jasmine
Testing Rich Client Side Apps with JasmineTesting Rich Client Side Apps with Jasmine
Testing Rich Client Side Apps with JasmineMark
 
DRb and Rinda
DRb and RindaDRb and Rinda
DRb and RindaMark
 
CoffeeScript - A Rubyist's Love Affair
CoffeeScript - A Rubyist's Love AffairCoffeeScript - A Rubyist's Love Affair
CoffeeScript - A Rubyist's Love AffairMark
 
Distributed Programming with Ruby/Rubyconf 2010
Distributed Programming with Ruby/Rubyconf 2010Distributed Programming with Ruby/Rubyconf 2010
Distributed Programming with Ruby/Rubyconf 2010Mark
 

More from Mark (15)

Mangling Ruby with TracePoint
Mangling Ruby with TracePointMangling Ruby with TracePoint
Mangling Ruby with TracePoint
 
AngularJS vs. Ember.js vs. Backbone.js
AngularJS vs. Ember.js vs. Backbone.jsAngularJS vs. Ember.js vs. Backbone.js
AngularJS vs. Ember.js vs. Backbone.js
 
A Big Look at MiniTest
A Big Look at MiniTestA Big Look at MiniTest
A Big Look at MiniTest
 
A Big Look at MiniTest
A Big Look at MiniTestA Big Look at MiniTest
A Big Look at MiniTest
 
GET /better
GET /betterGET /better
GET /better
 
CoffeeScript
CoffeeScriptCoffeeScript
CoffeeScript
 
Testing Your JavaScript & CoffeeScript
Testing Your JavaScript & CoffeeScriptTesting Your JavaScript & CoffeeScript
Testing Your JavaScript & CoffeeScript
 
Building an API in Rails without Realizing It
Building an API in Rails without Realizing ItBuilding an API in Rails without Realizing It
Building an API in Rails without Realizing It
 
5 Favorite Gems (Lightning Talk(
5 Favorite Gems (Lightning Talk(5 Favorite Gems (Lightning Talk(
5 Favorite Gems (Lightning Talk(
 
RubyMotion
RubyMotionRubyMotion
RubyMotion
 
Testing JavaScript/CoffeeScript with Mocha and Chai
Testing JavaScript/CoffeeScript with Mocha and ChaiTesting JavaScript/CoffeeScript with Mocha and Chai
Testing JavaScript/CoffeeScript with Mocha and Chai
 
Testing Rich Client Side Apps with Jasmine
Testing Rich Client Side Apps with JasmineTesting Rich Client Side Apps with Jasmine
Testing Rich Client Side Apps with Jasmine
 
DRb and Rinda
DRb and RindaDRb and Rinda
DRb and Rinda
 
CoffeeScript - A Rubyist's Love Affair
CoffeeScript - A Rubyist's Love AffairCoffeeScript - A Rubyist's Love Affair
CoffeeScript - A Rubyist's Love Affair
 
Distributed Programming with Ruby/Rubyconf 2010
Distributed Programming with Ruby/Rubyconf 2010Distributed Programming with Ruby/Rubyconf 2010
Distributed Programming with Ruby/Rubyconf 2010
 

Recently uploaded

Computer 10: Lesson 10 - Online Crimes and Hazards
Computer 10: Lesson 10 - Online Crimes and HazardsComputer 10: Lesson 10 - Online Crimes and Hazards
Computer 10: Lesson 10 - Online Crimes and HazardsSeth Reyes
 
Bird eye's view on Camunda open source ecosystem
Bird eye's view on Camunda open source ecosystemBird eye's view on Camunda open source ecosystem
Bird eye's view on Camunda open source ecosystemAsko Soukka
 
OpenShift Commons Paris - Choose Your Own Observability Adventure
OpenShift Commons Paris - Choose Your Own Observability AdventureOpenShift Commons Paris - Choose Your Own Observability Adventure
OpenShift Commons Paris - Choose Your Own Observability AdventureEric D. Schabell
 
9 Steps For Building Winning Founding Team
9 Steps For Building Winning Founding Team9 Steps For Building Winning Founding Team
9 Steps For Building Winning Founding TeamAdam Moalla
 
Building AI-Driven Apps Using Semantic Kernel.pptx
Building AI-Driven Apps Using Semantic Kernel.pptxBuilding AI-Driven Apps Using Semantic Kernel.pptx
Building AI-Driven Apps Using Semantic Kernel.pptxUdaiappa Ramachandran
 
UiPath Platform: The Backend Engine Powering Your Automation - Session 1
UiPath Platform: The Backend Engine Powering Your Automation - Session 1UiPath Platform: The Backend Engine Powering Your Automation - Session 1
UiPath Platform: The Backend Engine Powering Your Automation - Session 1DianaGray10
 
activity_diagram_combine_v4_20190827.pdfactivity_diagram_combine_v4_20190827.pdf
activity_diagram_combine_v4_20190827.pdfactivity_diagram_combine_v4_20190827.pdfactivity_diagram_combine_v4_20190827.pdfactivity_diagram_combine_v4_20190827.pdf
activity_diagram_combine_v4_20190827.pdfactivity_diagram_combine_v4_20190827.pdfJamie (Taka) Wang
 
20230202 - Introduction to tis-py
20230202 - Introduction to tis-py20230202 - Introduction to tis-py
20230202 - Introduction to tis-pyJamie (Taka) Wang
 
How Accurate are Carbon Emissions Projections?
How Accurate are Carbon Emissions Projections?How Accurate are Carbon Emissions Projections?
How Accurate are Carbon Emissions Projections?IES VE
 
Building Your Own AI Instance (TBLC AI )
Building Your Own AI Instance (TBLC AI )Building Your Own AI Instance (TBLC AI )
Building Your Own AI Instance (TBLC AI )Brian Pichman
 
Cybersecurity Workshop #1.pptx
Cybersecurity Workshop #1.pptxCybersecurity Workshop #1.pptx
Cybersecurity Workshop #1.pptxGDSC PJATK
 
Designing A Time bound resource download URL
Designing A Time bound resource download URLDesigning A Time bound resource download URL
Designing A Time bound resource download URLRuncy Oommen
 
KubeConEU24-Monitoring Kubernetes and Cloud Spend with OpenCost
KubeConEU24-Monitoring Kubernetes and Cloud Spend with OpenCostKubeConEU24-Monitoring Kubernetes and Cloud Spend with OpenCost
KubeConEU24-Monitoring Kubernetes and Cloud Spend with OpenCostMatt Ray
 
AI Fame Rush Review – Virtual Influencer Creation In Just Minutes
AI Fame Rush Review – Virtual Influencer Creation In Just MinutesAI Fame Rush Review – Virtual Influencer Creation In Just Minutes
AI Fame Rush Review – Virtual Influencer Creation In Just MinutesMd Hossain Ali
 
Comparing Sidecar-less Service Mesh from Cilium and Istio
Comparing Sidecar-less Service Mesh from Cilium and IstioComparing Sidecar-less Service Mesh from Cilium and Istio
Comparing Sidecar-less Service Mesh from Cilium and IstioChristian Posta
 
Secure your environment with UiPath and CyberArk technologies - Session 1
Secure your environment with UiPath and CyberArk technologies - Session 1Secure your environment with UiPath and CyberArk technologies - Session 1
Secure your environment with UiPath and CyberArk technologies - Session 1DianaGray10
 
Meet the new FSP 3000 M-Flex800™
Meet the new FSP 3000 M-Flex800™Meet the new FSP 3000 M-Flex800™
Meet the new FSP 3000 M-Flex800™Adtran
 
AI You Can Trust - Ensuring Success with Data Integrity Webinar
AI You Can Trust - Ensuring Success with Data Integrity WebinarAI You Can Trust - Ensuring Success with Data Integrity Webinar
AI You Can Trust - Ensuring Success with Data Integrity WebinarPrecisely
 

Recently uploaded (20)

Computer 10: Lesson 10 - Online Crimes and Hazards
Computer 10: Lesson 10 - Online Crimes and HazardsComputer 10: Lesson 10 - Online Crimes and Hazards
Computer 10: Lesson 10 - Online Crimes and Hazards
 
Bird eye's view on Camunda open source ecosystem
Bird eye's view on Camunda open source ecosystemBird eye's view on Camunda open source ecosystem
Bird eye's view on Camunda open source ecosystem
 
OpenShift Commons Paris - Choose Your Own Observability Adventure
OpenShift Commons Paris - Choose Your Own Observability AdventureOpenShift Commons Paris - Choose Your Own Observability Adventure
OpenShift Commons Paris - Choose Your Own Observability Adventure
 
9 Steps For Building Winning Founding Team
9 Steps For Building Winning Founding Team9 Steps For Building Winning Founding Team
9 Steps For Building Winning Founding Team
 
Building AI-Driven Apps Using Semantic Kernel.pptx
Building AI-Driven Apps Using Semantic Kernel.pptxBuilding AI-Driven Apps Using Semantic Kernel.pptx
Building AI-Driven Apps Using Semantic Kernel.pptx
 
UiPath Platform: The Backend Engine Powering Your Automation - Session 1
UiPath Platform: The Backend Engine Powering Your Automation - Session 1UiPath Platform: The Backend Engine Powering Your Automation - Session 1
UiPath Platform: The Backend Engine Powering Your Automation - Session 1
 
activity_diagram_combine_v4_20190827.pdfactivity_diagram_combine_v4_20190827.pdf
activity_diagram_combine_v4_20190827.pdfactivity_diagram_combine_v4_20190827.pdfactivity_diagram_combine_v4_20190827.pdfactivity_diagram_combine_v4_20190827.pdf
activity_diagram_combine_v4_20190827.pdfactivity_diagram_combine_v4_20190827.pdf
 
20230202 - Introduction to tis-py
20230202 - Introduction to tis-py20230202 - Introduction to tis-py
20230202 - Introduction to tis-py
 
How Accurate are Carbon Emissions Projections?
How Accurate are Carbon Emissions Projections?How Accurate are Carbon Emissions Projections?
How Accurate are Carbon Emissions Projections?
 
201610817 - edge part1
201610817 - edge part1201610817 - edge part1
201610817 - edge part1
 
Building Your Own AI Instance (TBLC AI )
Building Your Own AI Instance (TBLC AI )Building Your Own AI Instance (TBLC AI )
Building Your Own AI Instance (TBLC AI )
 
Cybersecurity Workshop #1.pptx
Cybersecurity Workshop #1.pptxCybersecurity Workshop #1.pptx
Cybersecurity Workshop #1.pptx
 
Designing A Time bound resource download URL
Designing A Time bound resource download URLDesigning A Time bound resource download URL
Designing A Time bound resource download URL
 
KubeConEU24-Monitoring Kubernetes and Cloud Spend with OpenCost
KubeConEU24-Monitoring Kubernetes and Cloud Spend with OpenCostKubeConEU24-Monitoring Kubernetes and Cloud Spend with OpenCost
KubeConEU24-Monitoring Kubernetes and Cloud Spend with OpenCost
 
AI Fame Rush Review – Virtual Influencer Creation In Just Minutes
AI Fame Rush Review – Virtual Influencer Creation In Just MinutesAI Fame Rush Review – Virtual Influencer Creation In Just Minutes
AI Fame Rush Review – Virtual Influencer Creation In Just Minutes
 
Comparing Sidecar-less Service Mesh from Cilium and Istio
Comparing Sidecar-less Service Mesh from Cilium and IstioComparing Sidecar-less Service Mesh from Cilium and Istio
Comparing Sidecar-less Service Mesh from Cilium and Istio
 
Secure your environment with UiPath and CyberArk technologies - Session 1
Secure your environment with UiPath and CyberArk technologies - Session 1Secure your environment with UiPath and CyberArk technologies - Session 1
Secure your environment with UiPath and CyberArk technologies - Session 1
 
Meet the new FSP 3000 M-Flex800™
Meet the new FSP 3000 M-Flex800™Meet the new FSP 3000 M-Flex800™
Meet the new FSP 3000 M-Flex800™
 
20230104 - machine vision
20230104 - machine vision20230104 - machine vision
20230104 - machine vision
 
AI You Can Trust - Ensuring Success with Data Integrity Webinar
AI You Can Trust - Ensuring Success with Data Integrity WebinarAI You Can Trust - Ensuring Success with Data Integrity Webinar
AI You Can Trust - Ensuring Success with Data Integrity Webinar
 

CoffeeScript for the Rubyist

  • 1. COFFEESCRIPT A Rubyist’s Love Affair @markbates
  • 6. Distributed Programming with Ruby Addison-Wesley 2009 http://books.markbates.com
  • 7. Programming in CoffeeScript Addison-Wesley 2012 http://books.markbates.com
  • 10. “ I need to come up with a scripting language for web browsers. I know! I'll make it cool and Lispy! ” Dramatic Re-enactment (1995)
  • 12. Yeah, So... Java is getting really popular. So we're going to need you to rewrite your language into something a bit more Java- esque and name it something like JavaScript.   Yeah, and we're going to need it in a week. Thanks, that'd be great. ” Dramatic Re-enactment (1995)
  • 13. var MyApp.Models.Product = Backbone.Model.extend({ isLiked: function() { var _ref; return ! ((_ref = this.like()) != null ? _ref.isNew() : void 0); }; like: function() { return new MyApp.Models.Like(this.get("like")); }; image: function(size) { var img; if (size == null) { size = "full"; } if (this.get("image") != null) { img = this.get("image")[size]; } if (img == null) { img = "/images/fallback/product_" + size + "_default.png"; } return img; }; });
  • 14. FAST FORWARD About 15 Years
  • 16. var MyApp.Models.Product = Backbone.Model.extend({ isLiked: function() { var _ref; return ! ((_ref = this.like()) != null ? _ref.isNew() : void 0); }; like: function() { return new MyApp.Models.Like(this.get("like")); }; image: function(size) { var img; if (size == null) { size = "full"; } if (this.get("image") != null) { img = this.get("image")[size]; } if (img == null) { img = "/images/fallback/product_" + size + "_default.png"; } return img; }; });
  • 17. class MyApp.Models.Product extends Backbone.Model isLiked: -> !@like()?.isNew() like: -> new MyApp.Models.Like(@get("like")) image: (size = "full") -> if @get("image")? img = @get("image")[size] unless img? img = "/images/fallback/product_#{size}_default.png" return img
  • 20. What is CoffeeScript? “A little language that compiles into JavaScript.”
  • 21. What is CoffeeScript? “A little language that compiles into JavaScript.” Easily integrates with your current JavaScript
  • 22. What is CoffeeScript? “A little language that compiles into JavaScript.” Easily integrates with your current JavaScript Easier to read, write, maintain, refactor, etc...
  • 23. What is CoffeeScript? “A little language that compiles into JavaScript.” Easily integrates with your current JavaScript Easier to read, write, maintain, refactor, etc... A Hybrid of Ruby and Python.
  • 24. What is CoffeeScript? “A little language that compiles into JavaScript.” Easily integrates with your current JavaScript Easier to read, write, maintain, refactor, etc... A Hybrid of Ruby and Python. Helpful.
  • 25. What CoffeeScript Is Not? Not Magic! Limited by what JavaScript can already do
  • 26. “ I’m happy writing JavaScript. I don’t need to learn another language. ”
  • 30. .MODEL SMALL DISP: MOV BL,VAL1 .STACK 64 ADD BL,VAL2 .DATA MOV AH,00H VAL1 DB 01H MOV AL,BL VAL2 DB 01H MOV LP,CL LP DB 00H MOV CL,10 V1 DB 00H DIV CL V2 DB 00H MOV CL,LP NL DB 0DH,0AH,'$' MOV V1,AL .CODE MOV V2,AH MAIN PROC MOV DL,V1 MOV AX,@DATA ADD DL,30H MOV DS,AX MOV AH,02H INT 21H MOV AH,01H INT 21H MOV DL,V2 MOV CL,AL ADD DL,30H SUB CL,30H MOV AH,02H SUB CL,2 INT 21H MOV AH,02H MOV DL,VAL2 MOV DL,VAL1 MOV VAL1,DL ADD DL,30H MOV VAL2,BL INT 21H MOV AH,09H MOV AH,09H LEA DX,NL LEA DX,NL INT 21H INT 21H LOOP DISP MOV AH,02H MOV DL,VAL2 MOV AH,4CH ADD DL,30H INT 21H INT 21H MAIN ENDP MOV AH,09H END MAIN LEA DX,NL INT 21H
  • 31. .MODEL SMALL DISP: .STACK 64 MOV BL,VAL1 ADD BL,VAL2 Assembly .DATA MOV AH,00H VAL1 DB 01H MOV AL,BL VAL2 DB 01H MOV LP,CL LP DB 00H MOV CL,10 V1 DB 00H DIV CL V2 DB 00H MOV CL,LP NL DB 0DH,0AH,'$' MOV V1,AL .CODE MOV V2,AH MAIN PROC MOV DL,V1 MOV AX,@DATA ADD DL,30H MOV DS,AX MOV AH,02H INT 21H MOV AH,01H INT 21H MOV DL,V2 MOV CL,AL ADD DL,30H SUB CL,30H MOV AH,02H SUB CL,2 INT 21H MOV AH,02H MOV DL,VAL2 MOV DL,VAL1 MOV VAL1,DL ADD DL,30H MOV VAL2,BL INT 21H MOV AH,09H MOV AH,09H LEA DX,NL LEA DX,NL INT 21H INT 21H LOOP DISP MOV AH,02H MOV DL,VAL2 MOV AH,4CH ADD DL,30H INT 21H INT 21H MAIN ENDP MOV AH,09H END MAIN LEA DX,NL INT 21H
  • 32. #include <stdio.h> C int fibonacci() { int n = 100; int a = 0; int b = 1; int sum; int i; for (i = 0; i < n; i++) { printf("%dn", a); sum = a + b; a = b; b = sum; } return 0; }
  • 33. public static void fibonacci() { Java int n = 100; int a = 0; int b = 1; for (int i = 0; i < n; i++) { System.out.println(a); a = a + b; b = a - b; } }
  • 34. def fibonacci Ruby a = 0 b = 1 100.times do printf("%dn", a) a, b = b, a + b end end
  • 35. “ I can write an app just as well in Java as I can in Ruby, but damn it if Ruby isn’t nicer to read and write! ”
  • 38. $(function() { $ -> success = (data) -> success = function(data) { if data.errors? if (data.errors != null) { alert "There was an error!" alert("There was an error!"); else } else { $("#content").text(data.message) $("#content").text(data.message); } $.get('/users', success, 'json') }; $.get('/users', success, 'json'); }); JavaScript CoffeeScript
  • 39. Syntax Rules No semi-colons (ever!) No curly braces* No ‘function’ keyword Relaxed parentheses Whitespace significant formatting
  • 40. Parentheses Rules # Not required without arguments: noArg1 = -> # do something # Not required without arguments: noArg2 = () -> # do something # Required without arguments: # Required with Arguments: noArg1() withArg = (arg) -> noArg2() # do something # Not required with arguments: withArg("bar") withArg "bar"
  • 41. Parentheses Rules # Bad: $ "#some_id" .text() # $("#some_id".text()); # Good: $("#some_id").text() # $("#some_id").text();
  • 43. Whitespace $(function() { success = function(data) { if (data.errors != null) { alert("There was an error!"); } else { $("#content").text(data.message); } }; $.get('/users', success, 'json'); });
  • 44. Whitespace $(function() { def fibonacci success = function(data) { a = 0 if (data.errors != null) { b = 1 alert("There was an error!"); 100.times do } else { printf("%dn", a) $("#content").text(data.message); a, b = b, a + b } end }; end $.get('/users', success, 'json'); });
  • 45. Whitespace $(function() { def fibonacci a = 0 success = function(data) { b = 1 if (data.errors != null) { alert("There was an error!"); 100.times do } else { printf("%dn", a) $("#content").text(data.message); a, b = b, a + b } end }; end $.get('/users', success, 'json'); });
  • 46. Whitespace $ -> success = (data) -> if data.errors? alert "There was an error!" else $("#content").text(data.message) $.get('/users', success, 'json')
  • 48. Conditionals if true doSomething() if true doSomething() doSomething() unless true unless true doSomething() if true doSomething() else doSomethingElse()
  • 49. Objects/Hashes someObject = {conf: "AlohaRubyConf", talk: "CoffeeScript"} someObject = conf: "AlohaRubyConf" talk: "CoffeeScript" someFunction(conf: "AlohaRubyConf", talk: "CoffeeScript")
  • 50. Objects/Hashes var someObject; someObject = { conf: "AlohaRubyConf", talk: "CoffeeScript" }; someObject = { conf: "AlohaRubyConf", talk: "CoffeeScript" }; someFunction({ conf: "AlohaRubyConf", talk: "CoffeeScript" });
  • 51. String Interpolation name = "AlohaRubyConf 2012" console.log "Hello #{name}" # Hello AlohaRubyConf 2012 console.log 'Hello #{name}' # Hello #{name}
  • 52. String Interpolation name = "AlohaRubyConf 2012" var name; console.log "Hello #{name}" name = "AlohaRubyConf 2012"; # Hello AlohaRubyConf 2012 console.log("Hello " + name); console.log 'Hello #{name}' # Hello #{name} console.log('Hello #{name}');
  • 53. Heredocs html = """ <div class="comment" id="tweet-#{tweet.id_str}"> <hr> <div class='tweet'> <span class="imgr"><img src="#{tweet.profile_image_url}"></span> <span class="txtr"> <h5><a href="http://twitter.com/#{tweet.from_user}" target="_blank">@#{tweet.from_user}</a></h5> <p>#{tweet.text}</p> <p class="comment-posted-on">#{tweet.created_at}</p> </span> </div> </div> """
  • 54. Heredocs var html; html = "<div class="comment" id="tweet-" + tweet.id_str + "">n <hr>n <div class='tweet'>n <span class= "imgr"><img src="" + tweet.profile_image_url + ""></ span>n <span class="txtr">n <h5><a href= "http://twitter.com/" + tweet.from_user + "" target= "_blank">@" + tweet.from_user + "</a></h5>n <p>" + tweet.text + "</p>n <p class="comment-posted-on">" + tweet.created_at + "</p>n </span>n </div>n</div>";
  • 55. Functions p = (name) -> console.log "Hello #{name}" p('AlohaRubyConf 2012')
  • 56. Functions var p; p = function(name) { return console.log("Hello " + name); }; p('AlohaRubyConf 2012');
  • 57. Functions p = (name)-> console.log "Hello #{name}" p('AlohaRubyConf 2012')
  • 58. Functions p = (name)-> console.log "Hello #{name}" CoffeeScript p('AlohaRubyConf 2012')
  • 59. Functions p = (name)-> console.log "Hello #{name}" CoffeeScript p('AlohaRubyConf 2012') p = ->(name) { puts "Hello #{name}" } Ruby 1.9 p.call('AlohaRubyConf 2012')
  • 60. Loops & Comprehensions for someName in someArray console.log someName for key, value of someObject console.log "#{key}: #{value}"
  • 61. Loops & Comprehensions var key, someName, value, _i, _len; for (_i = 0, _len = someArray.length; _i < _len; _i++) { someName = someArray[_i]; console.log(someName); } for (key in someObject) { value = someObject[key]; console.log("" + key + ": " + value); }
  • 62. Loops & Comprehensions numbers = [1..5] console.log number for number in numbers
  • 63. Loops & Comprehensions var number, numbers, _i, _len; numbers = [1, 2, 3, 4, 5]; for (_i = 0, _len = numbers.length; _i < _len; _i++) { number = numbers[_i]; console.log(number); }
  • 64. Loops & Comprehensions numbers = [1..5] console.log number for number in numbers when number <= 3
  • 65. Loops & Comprehensions var number, numbers, _i, _len; numbers = [1, 2, 3, 4, 5]; for (_i = 0, _len = numbers.length; _i < _len; _i++) { number = numbers[_i]; if (number <= 3) { console.log(number); } }
  • 66. Loops & Comprehensions numbers = [1, 2, 3, 4, 5] low_numbers = (number * 2 for number in numbers when number <= 3) console.log low_numbers # [ 2, 4, 6 ]
  • 67. Loops & Comprehensions var low_numbers, number, numbers; numbers = [1, 2, 3, 4, 5]; low_numbers = (function() { var _i, _len, _results; _results = []; for (_i = 0, _len = numbers.length; _i < _len; _i++) { number = numbers[_i]; if (number <= 3) { _results.push(number * 2); } } return _results; })(); console.log(low_numbers);
  • 68. Classes class Employee emp = new Employee() emp.firstName = "Mark"
  • 69. Classes var Employee, emp; Employee = (function() { Employee.name = 'Employee'; function Employee() {} return Employee; })(); emp = new Employee(); emp.firstName = "Mark";
  • 70. Classes class Employee constructor: (@options = {}) -> salary: -> @options.salary ?= "$250,000" emp = new Employee() console.log emp.salary() # "$250,000" emp = new Employee(salary: "$100,000") console.log emp.salary() # "$100,000"
  • 71. Classes var Employee, emp; Employee = (function() { Employee.name = 'Employee'; function Employee(options) { this.options = options != null ? options : {}; } Employee.prototype.salary = function() { var _base, _ref; return (_ref = (_base = this.options).salary) != null ? _ref : _base.salary = "$250,000"; }; return Employee; })(); emp = new Employee(); console.log(emp.salary()); emp = new Employee({ salary: "$100,000" }); console.log(emp.salary());
  • 72. Extending Classes class Manager extends Employee salary: -> "#{super} w/ $10k Bonus" manager = new Manager() console.log manager.salary() # "$250,000 w/ $10k Bonus"
  • 73. Extending Classes var Manager, manager, __hasProp = {}.hasOwnProperty, __extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor; child.__super__ = parent.prototype; return child; }; Manager = (function(_super) { __extends(Manager, _super); Manager.name = 'Manager'; function Manager() { var _base; Manager.__super__.constructor.apply(this, arguments); } Manager.prototype.salary = function() { return "" + Manager.__super__.salary.apply(this, arguments) + " w/ $10k Bonus"; }; return Manager; })(Employee); manager = new Manager(); console.log(manager.salary());
  • 74. Bound Functions class User constructor: (@name) -> sayHi: -> console.log "Hello #{@name}" bob = new User('bob') mary = new User('mary') log = (callback)-> console.log "about to execute callback..." callback() console.log "...executed callback" log(bob.sayHi) log(mary.sayHi)
  • 75. Bound Functions about to execute callback... Hello undefined ...executed callback about to execute callback... Hello undefined ...executed callback
  • 76. Bound Functions class User constructor: (@name) -> sayHi: -> console.log "Hello #{@name}" bob = new User('bob') mary = new User('mary') log = (callback)-> console.log "about to execute callback..." callback() console.log "...executed callback" log(bob.sayHi) log(mary.sayHi)
  • 77. Bound Functions class User constructor: (@name) -> sayHi: -> console.log "Hello #{@name}" bob = new User('bob') mary = new User('mary') log = (callback)-> console.log "about to execute callback..." callback() console.log "...executed callback" log(bob.sayHi) log(mary.sayHi)
  • 78. Bound Functions class User constructor: (@name) -> sayHi: => console.log "Hello #{@name}" bob = new User('bob') mary = new User('mary') log = (callback)-> console.log "about to execute callback..." callback() console.log "...executed callback" log(bob.sayHi) log(mary.sayHi)
  • 79. Bound Functions about to execute callback... Hello bob ...executed callback about to execute callback... Hello mary ...executed callback
  • 80. Bound Functions class User constructor: (@name) -> sayHi: => console.log "Hello #{@name}"
  • 81. Bound Functions var User, __bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; }; User = (function() { User.name = 'User'; function User(name) { this.name = name; this.sayHi = __bind(this.sayHi, this); } User.prototype.sayHi = function() { return console.log("Hello " + this.name); }; return User; })();
  • 82. FINALLY One of my favorite features
  • 83. Existential Operator if foo? console.log "foo"
  • 84. Existential Operator if (typeof foo !== "undefined" && foo !== null) { console.log("foo"); }
  • 87. Existential Operator console?.log "foo" if (typeof console !== "undefined" && console !== null) { console.log("foo"); }
  • 88. Existential Operator if currentUser?.firstName? console.log currentUser.firstName
  • 89. Existential Operator if currentUser?.firstName? console.log currentUser.firstName if ((typeof currentUser !== "undefined" && currentUser !== null ? currentUser.firstName : void 0) != null) { console.log(currentUser.firstName); }
  • 92. The Raven Once upon a mignight dreary while I pondered, weak and weary, Over many quaint and curious volume of forgotten lore - While I nodded, nearly napping, suddenly there came a tapping, As of some one gently rapping, rapping at my chamber door "'Tis some visiter". I muttered, "tapping at my chamber door" - "only this and nothing more." Ah distinctly I remember it was in the bleak December; And each separate dying ember wrought its ghost upon the floor. Eagerly I wished the morrow - vainly I had sought to borrow, From my books surcease of sorrow - sorrow For the lost Lenore - For the rare and radiant maiden whom the angels name Lenore - Nameless here For evermore
  • 93. The Raven var __indexOf = [].indexOf || function(item) { for (var i = 0, l = this.length; i < l; i++) { if (i in this && this[i] === item) return i; } return -1; }; while (I(pondered, weak && weary, Over(many(quaint && curious(volume in forgotten(lore - While(I(nodded, nearly(napping, suddenly(there(came(a(tapping, As in some(one(gently(rapping, rapping(at(my(chamber(door)))))))))))))))))))) {   Once(upon(a(mignight(dreary)))); } "'Tis some visiter".I(muttered, "tapping at my chamber door" - "only this and nothing more."); Ah(distinctly(I(remember(it(__indexOf.call(the(bleak(December)), was) >= 0))))); And(each(separate(dying(ember(wrought(its(ghost(upon(the(floor.Eagerly(I(wished( the(morrow - vainly(I(had(sought(to(borrow, From(my(books(surcease in sorrow - sorrow(For(the(lost(Lenore - For(the(rare && radiant(maiden(whom(the(angels(name(Lenore - Nameless(here(For(evermore)))))))))))))))))))))))))))))))))))));
  • 96. Matt Aimonetti “You should go to Mark’s Talk.”
  • 97. Matt Aimonetti “You should go to Mark’s Talk.” “Buy... his... book. It’s... Great.”
  • 99. Corey Haines “When I’m not engaged in auto- erotic asphyxiation I write CoffeeScript, you should too!”
  • 101. Konstantin Haase “I’m not negative, I’m just German, but I’m definitely positive about CoffeeScript!”
  • 102. What Didn’t I Cover? Default Arguments Operators Ranges The `do` keyword Splatted Arguments Plenty more! Scoping Security Strict Mode Fixes common ‘mistakes’
  • 104. Mahalo! myName = "Mark Bates" you.should buyBook("Programming in CoffeeScript") .at("http://books.markbates.com") you.should followMe(@markbates)

Editor's Notes

  1. \n
  2. \n
  3. \n
  4. \n
  5. \n
  6. \n
  7. \n
  8. \n
  9. \n
  10. \n
  11. \n
  12. \n
  13. \n
  14. \n
  15. \n
  16. \n
  17. \n
  18. \n
  19. \n
  20. \n
  21. \n
  22. \n
  23. \n
  24. \n
  25. \n
  26. \n
  27. \n
  28. \n
  29. \n
  30. \n
  31. \n
  32. \n
  33. \n
  34. \n
  35. \n
  36. \n
  37. \n
  38. \n
  39. \n
  40. \n
  41. \n
  42. \n
  43. \n
  44. \n
  45. \n
  46. \n
  47. \n
  48. \n
  49. \n
  50. \n
  51. \n
  52. \n
  53. \n
  54. \n
  55. \n
  56. \n
  57. \n
  58. \n
  59. \n
  60. \n
  61. \n
  62. \n
  63. \n
  64. \n
  65. \n
  66. \n
  67. \n
  68. \n
  69. \n
  70. \n
  71. \n
  72. \n
  73. \n
  74. \n
  75. \n
  76. \n
  77. \n
  78. \n
  79. \n
  80. \n
  81. \n
  82. \n
  83. \n
  84. \n
  85. \n
  86. \n
  87. \n
  88. \n
  89. \n
  90. \n
  91. \n