HTTP Server

A slightly more interesting example is an HTTP Server:

  1. require "http/server"
  2. server = HTTP::Server.new do |context|
  3. context.response.content_type = "text/plain"
  4. context.response.print "Hello world! The time is #{Time.local}"
  5. end
  6. address = server.bind_tcp 8080
  7. puts "Listening on http://#{address}"
  8. server.listen

The above code will make sense once you read the whole language reference, but we can already learn some things.

  • You can require code defined in other files:

    1. require "http/server"
  • You can define local variables without the need to specify their type:

    1. server = HTTP::Server.new ...
  • The port of the HTTP server is set by using the method bind_tcp on the object HTTP::Server (the port set to 8080).
    1. address = server.bind_tcp 8080
  • You program by invoking methods (or sending messages) to objects.

    1. HTTP::Server.new ...
    2. ...
    3. Time.local
    4. ...
    5. address = server.bind_tcp 8080
    6. ...
    7. puts "Listening on http://#{address}"
    8. ...
    9. server.listen
  • You can use code blocks, or simply blocks, which are a very convenient way to reuse code and get some features from the functional world:

    1. HTTP::Server.new do |context|
    2. ...
    3. end
  • You can easily create strings with embedded content, known as string interpolation. The language comes with other syntax as well to create arrays, hashes, ranges, tuples and more:

    1. "Hello world! The time is #{Time.local}"