# 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 }
end

puts factorial(5) # =&gt; 120

Now, here is the factorial method using recursion:

def factorial(n)
if n == 0
1
else
n * factorial(n-1)
end
end

puts factorial(5) # =&gt; 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 https://github.com/AxleMaxGit/blackjack-game

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 https://github.com/AxleMaxGit/blackjack-game/tree/master/app/ruby.

I am still doubting some aspects of what I have done so I posted a question on Stack Overflow here (http://stackoverflow.com/questions/20784408/am-i-passing-this-object-as-a-parameter-too-often)

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

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

Refactored into classes in separate files and added logic for players.

# 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 = Array.new(52)
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
else
cardname = n.to_s
cardvalue = n
end
deck[counter] = {:rank => (n.to_s), :suit => s, :cardname => cardname, :cardvalue => cardvalue}
counter +=1
end
end
deck.shuffle!

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.)

DECKSIZE = 52

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 &lt; DECKSIZE / SUITS.length
self.suit = SUITS[0]
elsif id &lt; DECKSIZE / SUITS.length*2
self.suit = SUITS[1]
elsif id &lt; DECKSIZE / SUITS.length*3
self.suit = SUITS[2]
else
self.suit = SUITS[3]
end
end
end

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

class Hand
attr_accessor :cards
def initialize(deck)
self.cards = (0..1).to_a.map { |id| deck.cards.pop }
end

def hand_total
puts "Hand Total"
total = 0
self.cards.each 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
else
total += c.rank.to_i
end
end
puts "The hand total so far is #{total}"
end
end

#BEGIN THE GAME ... Create & Shuffle the deck
deck1 = Deck.new
#Deal a starting hand
hand1 = Hand.new(deck1)
#Show the running total
hand1.hand_total
#Take another card
hand1.cards.push(deck1.cards.pop)
hand1.hand_total

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: http://guides.rubyonrails.org/testing.html

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. http://www.rubyinside.com/a-minitestspec-tutorial-elegant-spec-style-testing-that-comes-with-ruby-5354.html

The article above references a talk about Minitest by its author. http://www.everytalk.tv/talks/159-Cascadia-Ruby-Size-Doesn-t-Matter

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.

http://stackoverflow.com/questions/20714017/what-does-a-bang-before-a-variable-do/20714049?noredirect=1#comment31029834_20714049

15 TDD steps to a rails app

http://andrzejonsoftware.blogspot.com.au/2007/05/15-tdd-steps-to-create-rails.html

# 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) http://code.macournoyer.com/thin/usage/

How to do active model validations. My first use case was simply validating the presence of data in a form. (http://guides.rubyonrails.org/active_record_validations.html)

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. (http://railscasts.com/episodes/202-active-record-queries-in-rails-3)

How to use flash messages as a way to pass data between actions / controllers. (http://guides.rubyonrails.org/action_controller_overview.html#the-flash). 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. (http://stackoverflow.com/questions/20368717/rails-i-cant-pass-a-validation-error-in-a-redirect/20582976?noredirect=1#20582976)

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

Have another look at routing. (http://guides.rubyonrails.org/v2.3.11/routing.html). 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. (http://lifehacker.com/281626/jerry-seinfelds-productivity-secret)

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 (getbootstrap.com). 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.