Lock in $30 Savings on PRO—Offer Ends Soon! ⏳

Crystal introduction

Crystal introduction

at 2015/07/31 crystal meetup #1

Sho Kusano

July 31, 2015
Tweet

More Decks by Sho Kusano

Other Decks in Programming

Transcript

  1. Hello, World module IO # src/io.cr:218 def puts(*objects : _)

    objects.each do |obj| puts obj end nil end end LET’S GET STARTED OVERLOADING
  2. Hello, World module IO # src/io.cr:209 def puts(obj) self <<

    obj puts end end LET’S GET STARTED OVERLOADING
  3. Hello, World module IO # src/io.cr:209 def puts(obj) self <<

    obj puts end end LET’S GET STARTED OVERLOADING
  4. Hello, World module IO # src/io.cr:184 def <<(obj) obj.to_s self

    self end end LET’S GET STARTED OVERLOADING
  5. Overload with #to_s class String # src/string.cr:2262 def to_s self

    end # src/string.cr:2266 def to_s(io) io.write Slice.new(cstr, bytesize) end end LET’S GET STARTED OVERLOADING
  6. How to Make REFERENCE VS VALUE class RPoint property :x,

    :y end struct VPoint property :x, :y end Reference Value
  7. “ Differences REFERENCE VS VALUE The differences between a struct

    and a class are: •Invoking new on a struct allocates it on the stack instead of the heap •A struct is passed by value while a class is passed by reference •A struct implicitly inherits from Struct, which inherits from Value. A class implicitly inherits from Reference. http:/ /crystal-lang.org/docs/syntax_and_semantics/structs.html
  8. Let’s write codes REFERENCE VS VALUE def show(point) puts "1:

    #{point.x}x#{point.y}" point.x += 10 puts "2: #{point.x}x#{point.y}" end a = RPoint.new(10, 10) b = VPoint.new(10, 10) puts "Reference" show(a) show(a) puts "Value" show(b) show(b)
  9. Let’s run a code REFERENCE VS VALUE Reference 1: 10x10

    2: 20x10 1: 20x10 2: 30x10 Value 1: 10x10 2: 20x10 1: 10x10 2: 20x10
  10. “ What’s a macro MAGICAL MACRO Macros are methods that

    receive AST nodes at compile-time and produce code that is pasted into a program. http:/ /crystal-lang.org/docs/syntax_and_semantics/macros.html
  11. Usecase in REAL WORLD MAGICAL MACRO # crustache/spec/mustache_spec.cr require "./spec_helper"

    # for ~lambda.json test $calls = 0 {% for name in %w(interpolation sections inverted delimiters comments partials ~lambdas) %} {{ run “./generate_spec_from_json", “#{name.id}.json" }} {% end %}
  12. Usecase in REAL WORLD MAGICAL MACRO # power_assert.cr/src/power_assert.cr macro assert(expression,

    file = __FILE__, line = __LINE__) %result = {{ expression }} unless %result %ast = get_ast({{ expression }}) %breakdowns = %ast.breakdowns %message = String.build do |io| io << " " * PowerAssert.config.global_indent %ast.to_s(io) io << "\n" %breakdowns.to_s(io) end fail %message, {{ file }}, {{ line }} end %result end