IT 231 Ruby Tutorial on Lists

Overview

This tutorial reviews some basic statements for interacting with lists (also called arrays) using Ruby. To run these statements, you will to first open a Ruby console window.

Try out each of the commands. As much as possible, try to predict what each statement will do before you press Enter.

  1. animals = ["cat", "dog", "pig", "cow"]
  2. animals
  3. animals.length
  4. animals.include?("pig")
  5. animals.include? "pig"
  6. animals[3]
  7. animals[3].upcase
  8. animals.each { |x| puts x }
  9. animals.each { |x| puts x.length }

Finally, put the following lines in the file mylists.rb:

farm_animals = ["cat", "dog", "horse", "cow"]
farm_animals.each do |animal|
	if animal == "cow"
		puts "MOOO!"
	else
		puts "???"
	end
end

At a command console type: ruby mylists.rb (make sure that this file is in the same folder as the command console.

Or, with the interactive ruby interpreter, type: load mylists.rb (again making sure that the current folder has this file.

Modify the file so that it shows different outputs