One of the first things that made me go, “hmm…..” was the idea that in Ruby, everything’s an object and as such, can have methods associated with it.
Here’s a trivial example:
>> puts 22.to_s
=>”22″
The number, 22, is an object of type Integer. Integer objects have a number of methods, one of them is “to_s”, which transforms the number into a string. “puts” means “put string”, or print the string. The convention of using an arrow (=>) to point to a value means, “This is the value of the line above.” This is what IRB (interactive ruby) does. (The “>>” is the IRB prompt, so all the code is copied and pasted from IRB.)
In this case, the value of “puts 22.to_s” is the string “22″, NOT the number 22.
Arrays make a more interesting example, like this:
>> var1=[4,2,5,1,3]
=> [4,2,5,1,3]
Arrays are easily sorted using the “sort” method.
>> var1.sort
=> [1, 2, 3, 4, 5]
But, if you look at the value of var1 again, you’ll get:
>> var1
=> [4, 2, 5, 1, 3]
Which means the array isn’t sorted any longer. What’s going on?
Changes to Data and Method Naming Conventions
Sort doesn’t actually change the data in the array, it simply returns the sorted data. To actually sort the data, you’d need to use the “sort!” method:
>> var1.sort!
=> [1, 2, 3, 4, 5]
Looking at the value of the array, you’ll see the array is now sorted.
>> var1
=> [1, 2, 3, 4, 5]
! at the end of method names
Ruby programmers have developed a convention that methods ending in “!” actually change the data. The exclamation point is there to remind you that you’re really doing something to your data.
? at the end of method names
Likewise, Ruby programmers have developed a convention that methods ending in “?” are tests that return true or false. Eg:
>> var1.include?(3)
=> true
Which tests to see if the number three is in the array var1. If the number is not in the array, “include?” returns false. Eg:
>> var1.include?(15)
=> false