Teaching an 8 year old to code with Ruby

Here’s a very simple Ruby script I put together this evening for my daughter. She’s just started a book called Computer Coding for Kids and the first little Python script in there is a game where you are being chased by a ghost and have to guess which door to open. If the door you open has no ghost behind it, you get to continue to the next room and go again. If there is a ghost, the game ends.

After she got the code working, we discussed how we could use the same idea, but have a different story line to the game. Because it’s Halloween, she thought it would be great to pretend we were trick or treating and have to guess what kind of treat she would get each time she rang on a doorbell.

I put this script together for her to copy. I think it’s a good starting point for kids who are already confident with technology and who have perhaps played with things like scratch before and maybe have some concept of syntax.

guess = nil
trick_or_treat = nil
puts "It's Halloween"
puts "."
puts "."
puts "."
puts "And you're out trick or treating."
3.times { puts "." }
until guess != trick_or_treat do
  puts "You walk toward a house with a pumpkin outside and ring the bell."
  puts "The door creaks open and you shout 'Trick Or Treat?'"
  puts "What type of treat will you get?"
  print "Enter 1 for lollipop, 2 for chocolate bar, 3 for toffee apple: "
  trick_or_treat = 1 + rand(2)
  guess = gets.chomp.to_i
  if guess == trick_or_treat
    puts "Yay! you guessed correctly. That's another sweet in the bag."
  end
end
puts "Bad luck, you you guessed wrong, time to go home."

There’s quite a few concepts in this script that I threw in there to sort of lead my daughter’s learning. She’s done some basic programming in a few visual programming languages and a little Logo. She’s also done some introductions at school where they explained what an algorithm is and they did some very simple logic like comparing two numbers and drawing out some if conditions.

Here are the interesting (at least to us) points of discussion. When I’m doing this sort of teaching, I generally try not to answer for her unless it’s clear that she really has no idea what’s going on. In that case, I’ll usually take a step back and try to explain the concept in a different way and come back to the actual question I’ve posed another time to see if it “clicks”. This usually makes the learning a little more fun. It’s a game of discovery. Though, of course, takes longer than just shoveling information in 🙂

Anyway, on to the questions (note she didn’t necessarily get all of these – one or two I listened to her reasoning and then shelved until another day – especially the points on nil and variable initialisation):

* How many ways were there in the code to print three full stops? Do you think there could be other ways? If you could make up a computer language, how would you make the computer print three full stops?
* What is `nil`? Why is it there? Why are those two lines there setting variables to nil?
* What are variables anyway?
* Given the way the code works, what does `!=` mean? Here I prompted her a bit more – tell me what the code does in your own words…..etc
* What do you think `gets` does? (we ignored `chomp` and `to_i` for today)
* Why are there two equals signs for comparison

Models – Rails and ASP.NET MVC, Properties and Constraints


Some rather vague thoughts on models in Rails and ASP.NET MVC. Mostly out of interest in the different approaches rather than as a critique of either framework, because, well because that’s a different blog post….Let’s imagine, for this little ditty, that we are dealing with a blogging engine.

Properties

In Rails, properties don’t have to be explicitly declared in the models, so you get something like this:

class Post < ActiveRecord::Base
end

It's nice and clean, nice and simple, but, looking at the model, you have no idea what's in there. Instead, if you're a new developer on the project, you can scan through the schema.rb or dive straight into the database to find out.

Contrast that with ASP.NET MVC which takes a more explicit approach:

namespace YetAnotherBlogEngine.Models
{
    public class Post
    {
      public int Id (get; set;}
      public string Title {get; set;}
      public string Body {get; set;}
      public int Category_Id {get; set;}
      public datetime Date_Published {get; set;}
    }
}

So a new developer bounced in to the project knows what properties this model has by looking at the model rather than a schema.

I wonder, to myself mainly, if the differences are a function of the duck typed vs strongly typed nature of ruby vs c#, and the fact that with ASP.NET MVC the toolest (Visual Studio with its autocomplete and continual compilation process) was there before the framework, whereas Rails was developed as a framework before the toolset (Texmate, Vim + plugins, Host of other 3rd Party dev environments and obviously Sublime Text).

Constraints

Let's continue and add some sort of constraint - perhaps a blog post must have a title. That makes sense. I'm looking at the code first method in ASP.NET MVC because I think it provides a little more of a like-with-like comparison to Rails.

Rails takes the approach that model level validations are the way to go:

Model-level validations are the best way to ensure that only valid data is saved into your database. They are database agnostic, cannot be bypassed by end users, and are convenient to test and maintain

So, we can enhance our model like so:

class Post < ActiveRecord::Base
  validates :title, :presence => true
end

This, by itself, will not persist your constraint to the database schema. You would need to do that in your migration in Rails.

The Active Record way claims that intelligence belongs in your models, not in the database. As such, features such as triggers or foreign key constraints, which push some of that intelligence back into the database, are not heavily used.

and

Although Active Record does not provide any tools for working directly with such features, the execute method can be used to execute arbitrary SQL.

ASP.NET MVC on the other hand, is pretty strongly tied to SQL Server, or at least, the implicit assumption is that you're going to be using SQL Server, so applying constraints to a model (called data annotations) and then running your update-database (roughly the equivalent of a Rails migration) will apply your constraint at the database level as well as the model level (now I haven't validated every data annotation, but I'm talking about things like foreign keys and non-null values, and obviously this won't work with custom annotations).

So, our ASP.NET MVC model would look something like this:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.ComponentModel.DataAnnotations;

namespace YetAnotherBlogEngine.Models
{
    public class Post
    {
      public int Id (get; set;}
      [Required]
      public string Title {get; set;}
      public string Body {get; set;}
      public int Category_Id {get; set;}
      public datetime Date_Published {get; set;}
    }
}

I've added in the using statements, because you have to explicitly pop the DataAnnotations in there.

What I like about the Rails style, is looking at your model, you get a quick sense of what validations are going on because they are all collected at the top. With ASP.NET MVC, getting an overview of the constraints on a model takes a bit longer. Especially when your model grows in size, because you have to scan through all the properties to single out which ones have data annotations. Also, annotations in ASP.NET MVC are a bit of a mixed bag, because apart from constraints, you can also specify the front end display of a field. For example:

    [Display(Name = "Post Title")]
    public string Title {get; set;}

will cause your views to render "Post Title" as the label for the Title field by default. Anyway, lets not get into that too much because the data annotations are actually part of the entity framework rather than the mvc framework per se.

A true like for like comparison between ASP.NET MVC and Rails is not really possible. ASP.NET MVC, actually wants you to develop in a Model, View, View-Model, Controller paradigm. This extra layer in .NET makes more sense when you start to work with the strongly typed views and you realise that .NET doesn't actually want your views to use your models in anything but the most basic examples. Though often it feels like you are writing code for code's sake.

I'm not sure there is any punch line to this post other than maybe accepting that each framework has a philosophy and you should "render unto Caesar" in each framework and go with the overriding ideas, idioms and philosophies.

An ASP.NET MVC3 implementation of the cancerous Node.js Fibonacci code

I like to tinker with Node.js. Ted Dziuba doesn’t anymore. He thinks node.js is a cancer.
Obviously, a few people disagree – Joshua Kehn and Brian Beck. Ignoring all issues of relevance or flaimbait…and even ignoring all issues of original intent of the article, I was curious to see how C# under ASP.NET MVC3 fared in this little shootout.

I set up a simple MVC application. One controller. It looks like this:

public class HomeController : Controller
    {
        private int Fib(int? n){
            if (n < 2)
            {
                return 1;
            }
            else
            {
                return Fib(n - 2) + Fib(n - 1);
            }
        }

        public string Index(int? n)
        {
            if (string.IsNullOrEmpty(n.ToString()))
            {
                n = 2;
            }
            return Fib(n).ToString();
        }
    }

I ran it on an instance of IIS6.

$ time curl http://localhost/?n=40
default
real    0m0.343s
user    0m0.015s
sys     0m0.015s

Not too bad really. Haskell, however, is super duper fast – as Mathias Biilmann shows.

There’s a little fun for a Tuesday morning.

Principles not techniques

I like to think of coding in terms of principles vs techniques. I’ve met tons of good coders with lots of technique. Good technique. Rote technique. I’ve met very few coders who have good principles. A principle will let you look at anything code related…..and understand it….and if need be troubleshoot it.
Continue reading Principles not techniques

Rails on Windows – nil object when you didn’t expect it

If you jump between Linux and Windows XP like I do, sometimes you’ll pull your Rails app into the dreaded M$ platform, fire it up and be greeted with a lovely “Internal Server Error”. Naturally it goes on to say something like “You have a nil object when you didn’t expect it! You might have expected an instance of Array. The error occurred while evaluating nil.each” despite the fact that you’ve changed no code since last night when your app was running rather nicely in a Linux environment thank you very much. Sometimes you just need to hack your way out of a problem without worrying about the whys and wherefores – and that’s exactly what we are going to do here. So……open up configenvironmentsdevelopment.rb and find this line :

config.logger = Logger.new(config.log_path, 2, 10.kilobytes)

comment it out comme ca

#config.logger = Logger.new(config.log_path, 2, 10.kilobytes)

and fire it up again. All good? Yes? Excellent. Fixed. Why? Um. Log rotation in XP apparently. Something funny about it. Don’t really know. Haven’t investigated it much further because there is no way in hell I’m going to run a production Rails app in Windows. Ever.