Main Content

Ruby collections and strings - some new examples

Archive - Originally posted on "The Horse's Mouth" - 2010-02-03 07:28:50 - Graham Ellis

From yesterday's Ruby course - a whole set of new examples on Ruby collections - arrays (which are ordered lists) and hashes (which are unordered). In other words, you look somethng up in an array by its position number, whereas you look something up in a hash based on its unique key, and the way it's implemented, you cannot sort those keys - if you try, you get an array or arrays of two elements returned!

[example] - Sorting an array and iterating through it in various ways

[example] - Using an anonymous array to swap over two variables easily

[exampe] - Combining arrays with "and" and "or"

[example] - sorting a hash - (you can't, but this shows how to get the same effective result!)

[example] - multidimensional structures in Ruby - a hash or arrays in this case


Here are some other examples from yesterday too - string handling and exceptions:

[example] - lots of ways of defining and handling strings

[example] - cleaning up strings of text that are user input using string methods and regular expressions

[example] Using a constant to turn debug mode on and off - also a very good example of reading from and processing a file in Ruby