Session 6

What does this program do?

# Guess my number
puts "I'm thinking of a number between 1 and 100."
puts "What is it?"
my_number = rand(100) + 1
guess = gets.chomp.to_i
 
while guess > 0 && guess <= 100
  if guess == my_number
    puts "You guessed it! My number is " + guess.to_s + "."
    break
  elsif guess < my_number
    puts "Wrong, " + guess.to_s + " is too low."
  else
    puts "Wrong, " + guess.to_s + " is too high."
  end
  puts "Guess again."
  guess = gets.chomp.to_i
end

Arrays

Arrays are variables that contain lists of things

my_array = ['one', 'two', 'three']
empty_array = []
tic_tac_toe = [['X', 'O', 'O'], ['X', 'O', '-'], ['-', '-', 'X']]
 
# the whole array
puts my_array
puts
 
# by index
# starts at zero
puts my_array[0]
puts my_array[1]
puts my_array[2]
puts
 
# what's this?
puts my_array[3]
 
# nil is a special object that has no value
my_array[3] = 'four'
puts my_array[3]
 
puts
# arrays have an 'each' method
my_array.each do |element|
  puts "the next element is " + element
end
 
puts
# here's another iterator
3.times do 
  puts "hey there!"
end
 
# lots of array methods: google search "ruby array"
puts
# length returns the size of the array
puts my_array.length
# size does the same thing
puts my_array.size
 
puts
# reverse
my_array.reverse.each do |element|
  puts element
end
 
puts 
# join
puts my_array.join(', ')
 
puts
# first and last
puts "first: " + my_array.first
puts "last: " + my_array.last
 
puts
# push adds things to the end of the array
my_array.push "five"
puts my_array.join(', ')
 
puts
# pop removes things from the end of the array
my_array.pop
puts my_array.join(', ')
number = my_array.pop
puts my_array.join(', ')
 
puts
# clear empties the array
my_array.clear
puts "size: " + my_array.length.to_is

Alphabetize a bunch of words

puts "Type a bunch of words, one on each line."
puts "(empty line when you are done)"
 
words = []
word = gets.chomp
while word.length > 0
  words.push word
  word = gets.chomp
end
 
puts "ok, your words sorted are: "
words.sort.each do |next_word|
  puts next_word
end
Unless otherwise stated, the content of this page is licensed under Creative Commons Attribution-ShareAlike 3.0 License