In an effort to better recall stuff as I’m learning Ruby, I will be using my WP install for note-taking since no one visits this site ever (based on usage stats).
Ruby Basics
It’s multi-paradigm and interpreted. This means that Ruby is able to behave as a functional, object-oriented, and imperative language. As an aside, it seems like it would be confusing if you haphazardly combined all 3 styles in a single application, you should attempt to eliminate inconsistency and stick primarily with a single pradigm?
Functions
- puts(): prints a string. Returns nil
- gets(): gets a line of input from stdin, including \n, returns it.
Strings
‘Single-quoted’ or “Double-Quoted”. Single-quoted are limited to 2 escape sequences, \’ and \\. Double quoted can use the entire set of escape sequences. There is apparently a slight performance benefit to using single-quoted strings if you don’t need escape sequences.
Sequences I have never seen before in other languages…
- \c? and \C-?: CTRL+?
- \M-?: META+?
- \C-?\M-?: CTRL+META+?
- \e: ESC
- #{…} : Returns value of Ruby Expression inside {…}. Like back-ticks in Bash I guess.
Other ways to declare strings…
%q{str} or %Q{str} or %q;str; or %Q;str; all function as single and double quoted strings, respectively, returning ‘str’ or “str”.
variable = <<END
..
..
END : is known as “heredoc” format. This exists in bash and PHP so it’s nothing new.
to_s() : to_s() is the toString() method of Ruby.
Numbers
Fixnum and Bignum are the 2 number classes. -2^30 to 2^30-1 gets converted to Fixnum. Anything else is Bignum.
- 0x#### = Hex
- 0#### = Octal
- ##_## = #### (underscores are ignored)
There are also Floats that work as expected, but you can use exponential notation
- 1.2338
- 42.42e5
- ##.zero? = true/false
- ##.abs = abs(##)
Collections/Containers
You can create a collection by defining a range using .. or …
- col = 1..9
- col = 20…25
Trip-dots … will not include the last value in the collection. Double-dots .. will. The == operator is used to check for equality. Alternatively the .eql?() method can be used for this same purpose. === can be used to check for existance of an element in a collection. Alternatively, .include?() method does the same thing.
Arrays
Arrays in ruby work like they do in other languages, but there is no type restriction nor do you declare the type the array holds.
- empty_array = []
- also_empty = Array.new
- set_array = [ 'one', 'two', 'three' ]
- mixed = [ 'string', 10 ]
You can also create arrays from strings:
- %W( here are some words ) = ["here","are","some","words"]
- %w( some more ) = ["some","more"]
Note that capital W will process the string as if it’s double quoted, applying escape sequences as needed. On the other hand %w will use the literal interpretation of the string as with single quotes.
Objects also typically have a .to_a method, that converts the object’s contents to an array. This can be used on collections to get the array version of the collection.
>> col.to_a => [1, 2, 3, 4, 5, 6, 7, 8, 9]
Note that not all objects implement this method. You can add elements to an array by referencing a non-existant index in the array. Any un-defined indexes between the added item and the last item in the pre-appended array will be set to nil or ruby’s version of null.
>> arr = col.to_a => [1, 2, 3, 4, 5, 6, 7, 8, 9] >> arr[0] => 1 >> arr[10] = 'cheese' => "cheese" >> arr => [1, 2, 3, 4, 5, 6, 7, 8, 9, nil, "cheese"]
In addition, there are the .push() and .insert() methods. .push() takes a comma separated list of items to push on the end of the array. Insert takes an index and an item to insert at a specific point in the array. The index can be negative, in which case it is referring to counting backwards from the end of the array and inserting there.
There is also the << operator which pushes items on the end of an array. This can be chained to add multiple items.
Indexing
You can index an array like you’d expect, using [] operator. The cool thing about ruby is you can pass a collection of indexes and ruby will return the subset of indexes from the array that matches that range collection. ie. arr[2..5], or even the variable name of a collection. Crazy. If you send a collection that isn’t a range, you will get a TypeError.
.at(i) can also return an item at a specific index. .fetch(i, default) does the same thing, but lets you specify a default value to return when trying “fetch” an item. .values_at(list,of,array,indexes,default) does both what at and fetch can do, except it can take a list of indexes you want back.
.pop and .shift are methods which do as expected, .pop pops the last item from the array, and .shift shifts the first element off the array.
.delete_at(i) deletes the item at the index, and returns it. .delete(i) { default } also behaves like .delete_at, but you can specify a default value to return if the item in question doesn’t exist.
The Hash
A hash table. You can use objects to index items in the hash. Objects must implement .eql? method and must have a hash code to be used as keys.
- hash = { “something” => “else”, “another” => “thing” }
- hash = {}
- hash = Hash.new
- hash['something']
Ruby allows you to put newlines in a hash definition, using commas as delimeters. Hash.new(default) doesn’t set the values of the hash, it instead sets the default return value if a key doesn’t exist in the hash. You can index hashes like arrays. Hashes offer many of the same methods as arrays.
.has_key?(key) will return a boolean if it hash has key, .has_value?(val) will return a boolean if hash has a value. .empty? returns a boolean if hash is empty. .clear clears a hash’s contents.