Here are some initial Ruby operators and conventions that tripped me up, hopefully with coherent explanations so they won’t trip you up as well.
“!” in method names
It’s a convention that Ruby method names that end in “!” actually change the data. Eg:
var1 =[9, 8, 7, 6, 5, 4, 3, 2, 1, 0]
var1.sort
>> [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
You may think the above changes the values held bay the variable “var1″. But if you print out “var1″ again, you get the array in the original order:
var1
>> [9, 8, 7, 6, 5, 4, 3, 2, 1, 0]
The “sort” method returns the sort, but doesn’t change the actual order of the items in the array. But, The “sort!” method does: Eg:
var1.sort!
>> [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]var1
>> [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
If your method actually changes the data, have it end in an exclamation point.
“?” in method names
It’s a Ruby convention that methods that end in a question mark are tests that return “true” or “false”. Eg:
var1 =[9, 8, 7, 6, 5, 4, 3, 2, 1, 0]
var1.include?(5)
>> true
var1.include?(10)
>> false
If your method is intended as a test and returns “true” or “false”, name your method with a question mark.
“=” in method names
It’s a Ruby convention that method names that end in “=” are assignment methods. For example:
my.address= “1808 Ruby Way” or
my.address= (”1808 Ruby Way”)
assigns “1808 Ruby Way” to a variable (class, or instance).
%w{} is a Quick Way to Assign a List
You can create a list quickly out of a text string with %w{}. For example,
ary=%w{This is a test}
returns
["this", "is", "a", "test"]
class#method means class.method
In the documentation, you’ll find things things like
class#method (note the hash mark)
referring to something in code that’s actually writen
class.method (note the dot)
I don’t know the reasons why, but it’s confusing at first. But at least now you know.