The tutorial described by this post is brief but not as brief as it states (15 minutes) not at least for those that are seeing this technology for the very first time. At least for me, it took around 45 minutes to traverse it completely paying attention and trying to understand every part as well as the whole of it. Nevertheless, this tutorial is amazing. It is a blazing fast and complete tutorial, showing very important and practical features of the language via straightforward examples.
The same content in that tutorial will be presented here in a very brief way. It will be non-interactive like in there, though. This is just for remembering or reviewing purposes.
Let’s start:
Ruby is a japanese creation and it is revolutionary.
Type this on the prompt at hand:
This command returns a result: 8. Here we have the first important principle:
1) “All code gives an answer.” – Every command yields a result.
Then comes the string syntax with double quotes: “Jimmy”. As it is quick it promptly shows us how to reverse that name by executing the reverse method:
And get its length:
Get 5 times “Jimmy”:
reverse and length are English-language methods and * is a symbolic method.
Second principle:
2) Methods are action!
This causes an error:
Then try this:
In short:
- to_s is for string;
- to_i is for integer;
- to_a is for array.
This is an empty array:
A non-empty example, and obtaining the maximum of its values:
Store the array in a variable:
Type ticket in and see it printed back.
Reverse it in place (the exclamation sign in a method name indicates that it alters the contents of the object):
Text replace is done in this fashion (poem is a variable pointing to a String object):
poem['searched text'] = 'replacement text'
Square brackets are for targeting and finding things. Search and replace.
Reversing the poem:
Not good? Wanted to reverse the lines?
poem.lines.to_a.reverse.join
Instead of join it could have been to_s.
Analogous to the exclamation sign we have methods with a question mark, like this one:
poem.include? "some part"
It will return true when “some part” is a part of poem’s content. Pretty intuitive, huh? Keep following…
String methods e.g. downcase and delete are described here.
Hashes
Code:
books = {}
books["Full Dark, No Starts"] = :splendid
books["The Gunslinger"] = :good
books["If Tomorrow Comes"] = :awesome
{} is a hash. Its purpose is to pair up two things. In this case, book titles are receiving ratings.
But what are those words starting with a colon? This is the syntax for symbols. Unlike strings just one copy of it will lay in the memory for the process. Thus, its main purpose is performance. Symbols are tiny and fast.
To access a hash entry just type the name of the hash followed by the square brackets with the key to perform the lookup, but this time without the equal sign nor the value (assignment omitted), like this:
books["If Tomorrow Comes"]
One important thing to keep in mind is that the purpose of hashes is not sorting things up, but just pairing up two things, namely a key and a value. We can access a hash’s keys with e.g.
Create a new hash:
Then:
books.values.each { |rate| ratings[rate] += 1 }
The code within the curly braces is a block. A block is a bit of Ruby code that is attached to a method (the each method, above) and gets executed for each iteration of the method it is attached to. In this case, for each iteration, the each method gives the block an argument which was named rate.
Then at the end of the execution ratings will be a tally for how many times each rate was used.
Another example for a method that can have a block attached to it and executed – times:
5.times { print "Odelay!" }
The 5th part of the tutorial gives a taste of file manipulation. I will just toss the examples right here as they are very easy and intuitive to understand:
Dir.entries "/"
Dir["/*.txt"]
The Dir[] method is like entries but it searches for files with wildcard characters.
print File.read("/comics.txt")
FileUtils.copy('/comics.txt', '/Home/comics.txt')
File.open("/Home/comics.txt", "a") do |f|
f << "Cat and Girl: http://catandgirl.com/n"
end
do and end are the same as { and }. Rubyists often use them when the block goes on for many lines.
File.mtime("/Home/comics.txt")
The mtime gives us a Ruby Time object. If we want to check just what hour it was:
File.mtime("/Home/comics.txt").hour
Note: Methods with more than one argument have them separated with commas.
Methods and Classes
def load_comics( path )
comics = {}
File.foreach(path) do |line|
name, url = line.split(': ')
comics[name] = url.strip
end
comics
end
File.foreach opens a file and hands one line at a time to the block.
The split there is an axe laid, chopping the string in half, yielding the url and name.
strip removes extra spaces. Just to be safe.
The popup example (require ‘popup’) was omitted. Go to the tutorial and try it if so desired.
Now create a hash:
{} is a shortcut for it. They are the same.
What is ahead of us? Well, to start doing more complicated things, the best idea is to start by defining a new class. The focus now has become the construction of a blog in Ruby.
class BlogEntry
attr_accessor :title, :time, :fulltext, :mood
def initialize( title, mood, fulltext )
@time = Time.now
@title, @mood, @fulltext = title, mood, fulltext
end
end
entry = BlogEntry.new
Change the mood (access an attribute) without @ or $ (global variables) prepending the name, when outside the object:
mood there (outside the object) is an attribute accessor. Inside the object we have the instance variables (with the at-symbols prepending them).
Another identical way of expressing the @time assignment above, but outside of the object, is with this:
which is the attribute accessor alternative.
Using the initialize parameters:
entry2 = BlogEntry.new("In the Universe", :lost, "The Universe is infinite.")
Here are some more fundamental Ruby principles to remember:
3) Everything in Ruby is some kind of object. Classes explain objects. How a certain object works.
4) Accessors are variables attached to an object which can be used outside the object. (entry.time = Time.now)
5) Instance variables are the same variables used by accessors when inside the object. Like in a method definition. (@time = Time.now)
Now on to the very end. With Ruby we can do very neat things.
An array blog:
Try and guess what the following do:
blog.sort_by { |entry| entry.time }.reverse
blog.find_all { |entry| entry.fulltext.match(/cadillac/i) }
Add new entries to the blog with the << method:
Map
blog.map { |entry| entry.mood }
The map method cycles through the array replacing each item with something new. This new thing is that one inside the block. In the above example each item in the array gets replaced by its mood.
If we wanted to replace each of our blog entries with the name Bruce Willis we would do it like so: blog.map { “Bruce Willis” }
Links (Anything from the # character to the end of the line is a comment in Ruby):
http://ruby-doc.org/core/classes/Array.html # << method etc.
http://ruby-doc.org/core/classes/Enumerable.html # find_all method etc.
http://ruby-doc.org/core/classes/String.html # match method etc.
http://rubyonrails.org/ # The proper way to start using your Ruby knowledge, lad.
http://rubyonrails.org/screencasts # Creating a blog in 15 minutes (Rails).
One thing Rails has is easy methods for dates. Like, try: