Creating a Branch

Goals

  • Learn how to create a local branch in a repository

It’s time to do a major rewrite of the hello world functionality. Since this might take awhile, you’ll want to put these changes into a separate branch to isolate them from changes in master.

Create a Branch

Let’s call our new branch ‘greet’.

Execute:

  1. git checkout -b greet
  2. git status

NOTE: git checkout -b <branchname> is a shortcut for git branch <branchname> followed by a git checkout <branchname>.

Notice that the git status command reports that you are on the ‘greet’ branch.

Changes for Greet: Add a Greeter class.

lib/greeter.rb

  1. class Greeter
  2. def initialize(who)
  3. @who = who
  4. end
  5. def greet
  6. "Hello, #{@who}"
  7. end
  8. end

Execute:

  1. git add lib/greeter.rb
  2. git commit -m "Added greeter class"

Changes for Greet: Modify the main program

Update the hello.rb file to use greeter

lib/hello.rb

  1. require 'greeter'
  2. # Default is World
  3. name = ARGV.first || "World"
  4. greeter = Greeter.new(name)
  5. puts greeter.greet

Execute:

  1. git add lib/hello.rb
  2. git commit -m "Hello uses Greeter"

Changes for Greet: Update the Rakefile

Update the Rakefile to use an external ruby process

Rakefile

  1. #!/usr/bin/ruby -wKU
  2. task :default => :run
  3. task :run do
  4. ruby '-Ilib', 'lib/hello.rb'
  5. end

Execute:

  1. git add Rakefile
  2. git commit -m "Updated Rakefile"

Up Next

We now have a new branch called greet with 3 new commits on it. Next we will learn how to navigate and switch between branches.