Ruby List Tutorial
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.
- animals = ["cat", "dog", "pig", "cow"]
- animals
- animals.length
- animals.include?("pig")
- animals.include? "pig"
- animals[3]
- animals[3].upcase
- animals.each { |x| puts x }
- 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