recitation3 notes

Accessingelementsofarray

Info iconThis preview shows page 1. Sign up to view the full content.

View Full Document Right Arrow Icon
This is the end of the preview. Sign up to access the rest of the document.

Unformatted text preview: lo, Matz!” // Similarly, creates “Hello, Matz!” // Again, creates “Hello, Matz!” // Also creates “Hello, Matz!” 3. Accessing Strings a. line = “A horse! a horse! my kingdom for a horse!” b. line[18, 23] => “my kingdom for a horse!” // 18 = starting index location, // 23 = number of letters to retrieve c. line.index(“k”) => 21 // returns 1st index location where “k” appears 4. Comparisons a. hay == nicolay b. hay.eql? nicolay c. “a” <=> “v” // Compares hay with nicolay. Returns false. // Compares hay with nicolay. Returns false. // <=> is spaceship operator. Returns 0 if equal, -1 if less than, and 1 if greater than 6 5. Inserting a String in a String a. “Be carful .” .insert 6, “e” => “Be careful.” //Insert “e” at index 6 6. Substitute a Substring a. “That’s alll fokes”.gsub “alll”, “all” => “That’s all folks” 7. Reversing a String: a. “abcdefghijkl”.reverse => “lkjihgfedcba” Topic 8: Arrays 1. The Array class is one of Ruby’s built-in classes. Ruby arrays can hold objects such as String, Integer, Fixnum, Hash, Symbol, even other Array objects. Any object that Ruby can create, it can hold in an array. 2. Adding elements to a Ruby array will cause it to automatically increase in size 3. A Ruby array can hold objects of all different types, not just one type 4. Basic Array Functions a. months = Array.new // Creates a new array [ ] b. months.empty? // Returns boolean of whether months is empty c. months.size // Returns size of array d. months.length // Also returns size of array e. months.clear // Clears the array to [ ] f. months = Array.[ ] (“jan”, “feb”, “mar”, “dec”) //Creates array months g. months = [ nil, “Jan”, “Feb”, “Mar”, “Dec” ] //Another way to create array h. digits = Array(0 . . 9) //Creates array [1, 2, 3, 4, 5, 6, 7, 8, 9] 5. Iterating over Array a. sample = [“a”, “b”, “c”, “d”, “z”, 1, 5] sample.each { |e| print e } //prints out each element of sample 6. Accessing elements of array a. months = [“Jan”, “Feb”, “Mar”, “Apr”, “May”, “Jun”, “Jul”, “Aug”, “Dec” ] b. months[0] // returns Jan c. months[-1] // returns Dec d. m...
View Full Document

Ask a homework question - tutors are online