POST: Rubying LIKE A BOSS!

Ok, so I have been reading Chris Pine’s Learn to Program and I absolutely love it 😀

here is a link for any one interested in learning how to program in Ruby (you can read the book online for free!!) : https://pine.fm/LearnToProgram/

I’m on chapter 7, and I decided to share some of my code, in case anyone wants to learn too and would like to compare answers.

**the code looks much better on Sublime btw

1) a program that prints out leap years between two given years

puts “please enter the first year:”
year1 = gets.chomp.to_i
puts “please enter the second year:”
year2 = gets.chomp.to_i
puts “leap years between #{year1} and #{year2} are: ”

year = year1

while year >= year1 && year <= year2
if year%4 == 0 && year%100 == 0
if year%400 ==0
puts year
end
end
if year%4 == 0 && year%100 !=0
puts year
end
year += 1
end

2) Deaf Grandma program: she only answers when you shout (write in ALL CAPS), and only lets you go if you shout BYE three times in a row

command_2 = ” ”
command_1 = ” ”
counter = 0

puts “say something to grandma:”

while counter < 3

if command_1 != “BYE”
counter = 0
end

command_1 = gets.chomp

if (command_1 == command_1.upcase)
puts “NO, NOT SINCE 1938!”
else
puts “HUH! SPEAK UP SONNY!”
end

if command_1 == “BYE” && ((command_2 == ” “) || (command_2 == “BYE”))
counter += 1
command_2 = command_1

end
end

puts “BYE SONNY!”

3) a program that lets you enter any number of words that you want, then returns them sorted alphabetically (without using sort!) when you enter an empty line.

puts “please type the contents of your array, each followed by enter. When you’r done, just press enter again:”
input = gets.chomp
array = []

while input != “”
array.push “#{input}”
input = gets.chomp
end

l = array.length

hold=0

(l-1).times do |x|
if array[x] > array[x+1]
hold = array[x]
array[x] = array[x+1]
array[x+1] = hold
x += 1
else
x +=1
end
end

puts array

those are the ones I had most fun with!! code away and let me know if you have any ideas to improve my code!!

Advertisements