Category Archives: Ruby On Rails Learning

Ruby – Calculate Factorial Recursively


Solving Factorials Recursively

factorial is a non-negative integer, which is the product of all the positive integers less than or equal to itself. So, for example, the factorial of 5 is 120 (5 * 4 * 3 * 2 * 1). The factorial of 0 is always 1.

Without using recursion, we would calculate the factorial as follows in Ruby:

def factorial(n)
  (1..n).inject {|product, n| product * n }
puts factorial(5) # => 120

Now, here is the factorial method using recursion:

def factorial(n)
    if n == 0
        n * factorial(n-1)
puts factorial(5) # => 120

So how does the recursive method work? I found it useful to draw it out…

My Rails Learning Journey – “Breakable Toy” #2 – Blackjack in Rails – 02 Jan 2014

So I have wrapped up, for now, writing a Blackjack game in Ruby. It is pretty basic and runs in the console.

The Github repo for this version is at


Next I am going to try to build a Blackjack game in Rails. I don't think this kind of app is a good fit for Rails however I am going to give it a shot. Ultimately every app, challenge, etc is going to help me grow my understanding of Ruby, Rails, Git, etc.

My Rails Learning Journey – “Breakable Toy” #1 – Blackjack – 26 Dec 2013

Wow!! I think I made a breakthrough ove the last 2 days & nights. I think I finally get OOP, classes, methods, etc. It is such a great feeling.

Tonight I refactored my code and moved a bunch of methods into the classes they should always have belonged to.

I have set up a Github Repo for my code

I am still doubting some aspects of what I have done so I posted a question on Stack Overflow here (

I have started to read Practical Object-Oriented Design in Ruby (POODR) ( and it seems to be a great book. Even I can understand it so far. :-)

My Rails Learning Journey – “Breakable Toy” #1 – Blackjack – 24 Dec 2013

Last week at the local Ruby on Rails meetup – RoRo Sydney – Harry Curotta (@hiharryhere) gave a talk called "Rollercoaster on Rails: 1 year post career change". It was a great talk to hear for a person with hopes to cross the chasm from beginner to capable Rubyist . To hear that someone else has made it and how long it took them.

Harry talked about the idea of making some "breakable toys", some throw-away code that only really exists for the purpose of learning and experimentation. I had already had the same idea 2 weeks before but the term "breakable toys" sums the idea up perfectly and I am stealing it. Thanks Harry.

So it was Christmas eve and I have some time off work to sit down and code!! I woke up half dreaming / half daydreaming about writing a Blackjack program. A perfect breakable toy to help me learn. At the start of 2013 I took a Java course (that I really struggled with) and the main project was to write a BlackJack program. So there was the benefit of haviong talked through a similar object model to the one I will need but also I never really grasped the concepts of classes and object orientation. I understood the idea but I couldn't apply it.

I lay there thinking through the problem for what felt like a couple of hours until I was literally aching to get out of bed and code it. I think I am hooked on this stuff. It makes me feel so great to be so into programming because it might be the hardest thing I have ever attempted and I feel like, through perserverance, I am finally starting to crack it!

I decided to start with the first object. Simple. What do I need? I need a deck of cards. I quickly realised that it would be far simpler to switch my thinking from Rails to Ruby (which may not be true to an experienced programmer but I wanted to focus on the logic) and ignore the web framework for now. Just get the logic working. So I spent the day with Sublime Text 2 and BASH building the beginnings of my BlackJack app.

The first cut was quite procedural, not at all object oriented.

rank = Array(1..13)
suits = ["Hearts", "Diamonds", "Spades", "Clubs"]
deck =
counter = 0

suits.each do |s|
  rank.each do |n|
    if n == 1
      cardname = "Ace"
      cardvalue = 11
    elsif n == 11
      cardname = "Jack"
      cardvalue = 10
    elsif n == 12
      cardname = "Queen"
      cardvalue = 10
    elsif n == 13
      cardname = "King"
      cardvalue = 10
      cardname = n.to_s
      cardvalue = n
    deck[counter] = {:rank => (n.to_s), :suit => s, :cardname => cardname, :cardvalue => cardvalue}     
    counter +=1

So I decided to try and build some classes and make it a bit more "OO". I set it up for a future with multiple decks and added the ability to deal a hand and take additional cards. All of a sudden it is 1am on Christmas day and time to go to bed. On another date I might have stayed up all night. (Note: There is a commented out easier way to build the deck but I was playing around so I've left in an alternative that I think allows for changes in the number of ranks if I was using a different style of playing cards or in a different game altogether.)


class Card
  RANKS = %w(2 3 4 5 6 7 8 9 10 J Q K A)
  SUITS = %w(Spade Heart Club Diamond)

  attr_accessor :rank, :suit
  def initialize(id)
    self.rank = RANKS[id % 13]
    #easier way to generate suits
    #self.suit = SUITS[id % 4]
    if id < DECKSIZE / SUITS.length
      self.suit = SUITS[0]
    elsif id < DECKSIZE / SUITS.length*2
      self.suit = SUITS[1]
    elsif id < DECKSIZE / SUITS.length*3
      self.suit = SUITS[2]
      self.suit = SUITS[3]   

class Deck
  attr_accessor :cards
  def initialize
    # shuffle array and init each Card
    puts "Creating & Shuffling the Deck" = (0..(DECKSIZE-1)) { |id| }
    #unshuffled = (0..(DECKSIZE-1)) { |id| }

class Hand
  attr_accessor :cards
  def initialize(deck)
    # start with 2 cards from the deck = (0..1) { |id| }

  def hand_total
    puts "Hand Total"
    total = 0 do |c|
      puts "C.RANK is #{c.rank}"
      #puts c.rank.to_i
      if c.rank == "A" 
        total += 11
      elsif c.rank == "J" || c.rank == "Q" || c.rank == "K"
        total += 10 
        total += c.rank.to_i
    puts "The hand total so far is #{total}"

#BEGIN THE GAME ... Create & Shuffle the deck
deck1 =
#Deal a starting hand
hand1 =
#Show the running total
#Take another card

There are probably a million ways to make this code better but I went to bed feeling pleased that I had made some progress today.

My Rails Learning Journey – Testing – TDD – 21 Dec 2013

Learn Rails 4 native testing:

Watched a great video tutorial from Rails for Zombies.

Read a great post on how to use MiniTest. I think it is the default testing library in Ruby now.

The article above references a talk about Minitest by its author.

Made a schoolboy error when trying to understand a bang in front of a statement instead of after. Posted a Stack Overflow question then slapped my forehead when I got the answer.

15 TDD steps to a rails app

Other stuff I have learned before I started this blog

How to replace the default Rails 4 web servr, WebBrick with a different web server that is less verbose (Thin web server)

How to do active model validations. My first use case was simply validating the presence of data in a form. (

How to use the rails console (rails c) to play around with the active record query interface. Basically to create and retrieve records from the sqlite3 database. Railscasts has a pretty good lesson on this. (

How to use flash messages as a way to pass data between actions / controllers. ( In my case the first tome the need for this arose when I was wrestling with how to capture and pass model validation error messages between controllers. See the Stack Overflow question for more details on that one. (



My Rails Learning Journey – HTTP Headers & Routing – 22 Dec 2013

Learn about HTTP Headers: (

Have another look at routing. ( I’m hoping to get a grip on nested routes.

Here’s an interesting point. The sequence of the routes in routes.rb is important. “The request will be dispatched to the first matching route. If there is no matching route, then Rails returns HTTP status 404”





Introduction – Why This Blog?

This blog is my way of capturing the things I learn as I try to go from zero to hero as I learn to program. There are 2 key things that led me here.

1. At the start of 2013 I heard that billionaire Mayor of New York, Michael Bloomberg had announced that he was going to learn to code this year. (actually it turnd out that it had happened in 2012!!).

That was enough of a prompt for me to consider coding a new form of literacy and I needed to up-skill. I began my journey in January 2013 with a university Java course. The computer science learnings were good and helped me understand the key principles that underly any programming language but I found the teacher very boring and disengaged and I found Java a difficult language for a beginner. At the end of the course I could write simple apps in the command line (e.g. a blackjack game) but we didn't learn any web frameworks. In the second half of the year I learned Ruby on Rails at General Assembly. The course used a learn by doing approach and so I felt that I learned a lot more. Plus Rails is about the easiest way to get a dynamic website built in munites.

2. On 30 Nov 2013 I read a LifeHacker article about the Seinfeld calendar. It is such a great and simple idea that has transformed the amount of progress that I have made towards being a competent programmer. (

I was stuck on one topic (associations) and was feeling like giving up. But then I read about the Seinfeld calendar. Basically it is about doing something, anything, every day.

Image: An example Seinfeld calendar

This totally changed my approach. In order to do something on day 1 I used some simplescaffolds and played around with them. Then I wanted to make it look nicer so I spent a few days playing with Bootstrap ( That led me down a CSS rabbit hole for another few days. It was equal measure of fun and frustration but I was learning something every day.

Image: Github's implementation of a Seinfeld calendar

The only problem with the Github calendar is that my learning is sometimes about reading and sometimes about experimenting on my laptop where I don't make commits. So I have started this blog to document my progress as I learn.

Perhaps if I ever decide to try and work as a Rails developer this blog might provide some insight ot my prospective employer. Or otherwise I hope that someone else that is on the journey from zero to programmer hero might find some reassurance that it came be done if you just stick to it and keep mking progress every day.