Skip to content

Instantly share code, notes, and snippets.

@javierg
Forked from smathy/Chapter 05.markdown
Created November 10, 2009 19:12
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save javierg/231173 to your computer and use it in GitHub Desktop.
Save javierg/231173 to your computer and use it in GitHub Desktop.

Chapter 2

Hours in a year (assuming is not a leap year)

hours_per_year = 365*24
puts hours_per_year

Minutes in a decade

minutes_per_decade = hours_per_year*10*60
puts minutes_per_decade

Your age in seconds

today = Time.now
bday = Time.utc(1976,3,2,15,0,0)
puts today-bday

Our dear author's age

authors_seconds_lived = 1025000000
authors_age = (((authors_seconds_lived/60)/60)/24)/365

puts authors_age

Chapter 5

Full name greeting

puts 'Hello! What\'s your first name?'
first_name = gets.chomp
puts 'Do you have a middle name?'
middle_name = gets.chomp
puts 'What\'s your family name?'
last_name = gets.chomp
puts 'Hello ' + first_name + ' ' + middle_name + ' ' + last_name
puts 'Nice to meet you ' + ':-)'

Bigger, better favorite number

puts 'Hello estranger! what\'s your favorite number?'
favorite_number = gets
better_favorite_number = favorite_number.to_i + 1
puts 'You should better have ' + better_favorite_number.to_s

Chapter 6

Angry boss

puts 'What do you want now?'
question = gets.chomp
answer = 'WHADDAYA MEAN "' + question.upcase + '"?!? YOU\'RE FIRED!!'
puts answer

Table of contents

puts 'Table of contents'.center(48)
puts ''
puts 'Chapter 1: Getting Started               page  1'
puts 'Chapter 2: Getting Started               page  9'
puts 'Chapter 3: Getting Started               page 13'

Chapter 7

99 Bottles of Beer on the Wall

objects_name = "bottle"
total_objects_on_the_wall = 99
object_type = ""

while true
  puts "What do you want to count?"
  object_type = gets.chomp
  if object_type != "" 
      break
  end
end

while total_objects_on_the_wall>0
  if total_objects_on_the_wall>1 
          plural = "s"
  else 
          plural = "" 
  end
  print "#{total_objects_on_the_wall} #{objects_name+plural} of #{object_type} on the wall, "
  puts  "#{total_objects_on_the_wall} #{objects_name+plural} of #{object_type}."
  total_objects_on_the_wall = total_objects_on_the_wall-1 
end

plural = "s"
total_objects_on_the_wall

puts "No more #{objects_name+plural} of #{object_type} on the wall, no more #{objects_name} of #{object_type}."
puts "Go to the store and buy some more, #{total_objects_on_the_wall} #{objects_name+plural} of #{object_type} on the wall."

Deaf grandma

puts "HELLO SONNY, HOW ARE YOU?"

while true
        sonny_question = gets.chomp
        if sonny_question == sonny_question.upcase
                puts "NO, NOT SINCE 1938!"
                break
        end
        puts "HUH?! SPEAK UP, SONNY!"
end    

Deaf grandma extended

puts "HELLO SONNY, HOW ARE YOU?"

while true
        sonny_question = gets.chomp
        if sonny_question == "BYE"
                puts "AND THEN..."
                break   
        end
        if sonny_question == sonny_question.upcase
                random_year = 1928 + rand(80)
                puts "NO, NOT SINCE #{random_year}!"
                puts "WHAT ELSE SONNY?"
        else    
           puts "HUH?! SPEAK UP, SONNY!"
        end
end  

Leap years

puts "This program will show all the leap years in a given range"

while true
        puts "Starting year: "
        start_year = gets.to_i
        puts "Ending year: "
        end_year  =  gets.to_i
        if start_year.to_i >=0 and end_year>start_year 
               break
        else
            puts "This is an invalid range."
        end
end

current_year = start_year


while current_year < end_year
        if (current_year%4 == 0 and current_year%100!=0) || current_year%400!=0
                puts "Leap year #{current_year}"   
        end
        current_year = current_year+1
end

Chapter 8

Building and sorting an array

def clear
    if RUBY_PLATFORM =~ /linux|i686-darwin9/ then
            system "clear"
    elsif RUBY_PLATFORM =~ /mswin32/ then
            system "cls"
    end
end


def msg(str,col_width)
    puts "=".center(col_width,"=")
    puts str.center(col_width)
    puts "=".center(col_width,"=")
end


clear
instructions=[]
instructions.push "Please enter as many words as you want"
instructions.push "[only one word per line]"
instructions.push "to exit, enter an empty line"
longest_line = 0
instructions.each do |inst|
    if longest_line<inst.length
            longest_line = inst.length 
    end
end

longest_line += 10

puts "=".center(longest_line,"=")
instructions.each do |inst|
    puts inst.center(longest_line)
end
puts "=".center(longest_line,"=")

text_list =[]

while true
    item_on_list = gets
    if item_on_list.include? " " 
            msg("Remember, one word per line",longest_line)
    elsif item_on_list.length == 1 
             msg("Good Bye!",longest_line)
            break
    else
            text_list.push item_on_list
    end
end

if text_list.length>0
    clear
    msg("YOUR SORTED WORD LIST",longest_line)
    puts ""
    sorted_words = text_list.sort
    sorted_words.each do |word|
            puts "#{sorted_words.index(word)+1}.- #{word}"
    end
    puts ""
    puts "=".center(longest_line,"=")
end

Table of contents, revisited

def clear
        if RUBY_PLATFORM =~ /linux|i686-darwin9/ then
           system "clear"
           line_width = terminal_size()[0]
        elsif RUBY_PLATFORM =~ /mswin32/ then
           system "cls"
           line_width = 90
        end
        line_width
end

def terminal_size
            `stty size`.split.map { |x| x.to_i }.reverse
end

line_width = clear

contents =[["Getting Started",1],["Numbers",9],["Letters",13]]
puts "_".center(line_width,"_")
puts "Table of Contents".center(line_width)
puts "_".center(line_width,"_")
puts ""
contents.each do |chapters|
    if chapters[1]>9
            fix_page_space = ""
    else
            fix_page_space =" "
    end
    title_col = "    Chapter #{contents.index(chapters)+1}: #{chapters[0]}"
    print title_col
    puts  "page #{fix_page_space}#{chapters[1]}".rjust(line_width-title_col.length-4,".")
end     
puts ""
puts "_".center(line_width,"_")

Chapter 9

Improved ask method

#!/usr/bin/ruby

def set_defaults
  if RUBY_PLATFORM =~ /linux|i686-darwin9/ then
     system "clear"
     terminal_size = `stty size`.split.map { |x| x.to_i }.reverse
     line_width = terminal_size[0]
  elsif RUBY_PLATFORM =~ /mswin32/ then
     system "cls"
     line_width = 90
  else
     line_width = 90
  end
     line_width
end

def randomize_array(arr)
   arr.sort_by{rand}
end

def get_random_item(arr)
   seed = rand(arr.length-1)
   arr[seed]
end

def hr(width,char='_')
      puts char.center(width,char)
end

def ask question
    while true
      puts question
        case gets.chomp.downcase
            when 'yes' then
                    if question.rindex(/bed/) == nil
                       $order.push question.sub(/\?/,'').scan(/\b\w*$/).join
                    end
                    return true
            when 'no'  then return false
            else puts 'Please answer "yes" or "no"'
        end
    end
end

food     = ["tacos","burritos","chimichangas","sopapillas","flautas"]
drinks   = ["horchata","margaritas","tequila"]
personal = ["wet the bed"]
line_width = set_defaults
hr(line_width)
puts 'Hello stranger. Welcome to "El Taco Grande"'.center(line_width)
puts 'We have some sugestions on our menu'.center(line_width)
hr(line_width)
puts

random_food = randomize_array(food)

$order = []

food.each do |item|
   ask "Do you like #{item}?"
   if item == random_food[0]
           ask "Do you #{get_random_item(personal)}"
   elsif item == random_food[1]
           ask "Do you like drinking #{get_random_item(drinks)}"
   end
end

set_defaults
puts
puts "DEBRIEFING:"
hr(line_width,"=")
puts 'THANK YOU!'.center(line_width)
hr(line_width)
puts "Order details".center(line_width)
$order.each do |item|
   puts item.center(line_width)
end
hr(line_width)
puts
puts "your order will be ready in 45 minutes!".center(line_width)
puts
hr(line_width)

Old-school Roman numerals

def set_defaults if RUBY_PLATFORM =~ /linux|i686-darwin9/ then system "clear" terminal_size = stty size.split.map { |x| x.to_i }.reverse line_width = terminal_size[0] elsif RUBY_PLATFORM =~ /mswin32/ then system "cls" line_width = 90 else line_width = 90 end line_width end

def arabic_to_roman number
    
    if number <=0 || number>3000    
            return "The entered value can not be represented as a Roman Number"
    end
    
    roman_numeral = ""
    numbers_equiv = [[1000,"M"],[500,"D"],[100,"C"],[50,"L"],[10,"X"],[5,"V"],[1,"I"]]
    roman_set = [0,0,0,0,0,0,0]
    
    numbers_equiv.each_index do |set|
       if number >= numbers_equiv[set][0]
          roman_set[set] = number/numbers_equiv[set][0]
          number -= roman_set[set]*numbers_equiv[set][0]
       end
    end
    
    roman_set.each_index do |current|
       roman_set[current].times { roman_numeral += numbers_equiv[current][1] }
    end
    "Your Roman Number is: #{roman_numeral}"
end 
    
line_width = set_defaults

while true
    puts "_".center(line_width,"_")
    puts "Enter a number to convert".center(line_width)
    puts "to exit type [x]".center(line_width)
    puts "_".center(line_width,"_")
    puts
    print "Number: "
    num = gets.chomp
    if num == 'x'
       set_defaults
       puts "Bye!"
       break
    end
    set_defaults
    puts "_".center(line_width,"_")
    puts "  #{arabic_to_roman num.to_i}  ".center(line_width,"#")
    puts "_".center(line_width,"_")
    puts
end

Modern Roman numerals

$line_width = 90

def set_defaults
   if RUBY_PLATFORM =~ /linux|i686-darwin9/ then
      system "clear"
      terminal_size = `stty size`.split.map { |x| x.to_i }.reverse
      $line_width = terminal_size[0]
   elsif RUBY_PLATFORM =~ /mswin32/ then
       system "cls"
   end
end

def arabic_to_roman number
    if number <=0 || number>3000
       return "The entered value can not be represented as a Roman Number"
    end
    roman_numeral = ""
    # I Like Arrays
    numbers_equiv = [
       [1000,"M"],
       [900,"CM"],
       [500,"D"],
       [400,"CD"],
       [100,"C"],
       [90,"XC"],
       [50,"L"],
       [40,"XL"],
       [10,"X"],
       [9,"IX"],
       [5,"V"],
       [4,"IV"],
       [1,"I"]
    ]
    # Maybe in this one, I should used the {X=>"Y"} syntaxist, but ... nhe... latter
    numbers_equiv.each do |set|
       if number >= set[0]
          to_roman = number.divmod(set[0])
          roman_numeral += set[1]*to_roman[0]
          number = to_roman[1]
       end
    end
    "Your Roman Number is: #{roman_numeral}"
end

set_defaults

while true
    puts "_".center($line_width,"_")
    puts "Enter a number to convert".center($line_width)
    puts "to exit type [x]".center($line_width)
    puts "_".center($line_width,"_")
    puts
    print "Number: "
    num = gets.chomp
    if num == 'x'
       set_defaults
       puts "Bye!"
       break
    end
    set_defaults
    puts "_".center($line_width,"_")
    puts "  #{arabic_to_roman num.to_i}  ".center($line_width,"#")
    puts "_".center($line_width,"_")
    puts
end

Chapter 10

##Sorting

#!/usr/bin/ruby

#This was Paul Idea... I am afraid of doing this kind of stuff, and check... ruby arry[].sort is not using it... class String include Comparable alias_method :old_compare, :"<=>" def <=>(other) self.downcase.old_compare(other.downcase) end

end

def array_sort arr recursive_sort arr, [] end

def recursive_sort unsorted, sorted return sorted if unsorted.length < 1

to_sort = []        
word = unsorted.shift

unsorted.each do |element|
    if  element < word
        to_sort.push word
        word = element
    else
        to_sort.push element
    end 
end 

sorted.push word

recursive_sort to_sort, sorted

end

test =[ "Sinaloa","Chihuahua","Nuevo León","Tamaulipas", "Sonora","Nayarit","baja California", "Baja California Sur", "Coahuila","Zacatecas","Durango","Guanajuato","Jalisco", "Veracruz","San Luis Potosí", "a","aa", "aaab", "ab" ]

puts "===== my sort =====" puts array_sort test puts puts "==== sort method ====" puts test.sort

Shuffle

Dictionary sort

Expanded english_number

Wedding number

Ninety-nine Bottles of Beer on the Wall

Chapter 11

Safer picture downloading

Build your own playlist

Build a better playlist

Chapter 12

One billion seconds!

Happy birthday!

Party like it's roman_to_integer 'mcmxcix'!

Birthday helper!

Chapter 13

Extend the built-in classes

Orange tree

Interactive baby dragon

Chapter 14

Even better profiling

Grandfather clock

Program logger

Better program logger

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment