Ruby On Rails Classroom image

Neha  Jaggi / Professional / Web Technology

To post your Question Join Classroom
Lesson Topics's No:-  |1 | 2|Last
Lessons:- Objects and Message Passing

  Objects and Message Passing

Everything in Ruby, including strings and even nil, is an object. We’ll see the technical meaning of this in Section 4.4.2, but I don’t think anyone ever understood objects by reading the definition in a book; you have to build up your intuition for objects by seeing lots of examples.

                 It’s easier to describe what objects do, which is respond to messages. An object like a string, for example, can respond to the message length, which returns the number of characters in the string:

>> "foobar".length # Passing the "length" message to a string
=> 6

Typically, the messages that get passed to objects are methods, which are functions defined on those objects.4 Strings also respond to the empty? method: 

>> "foobar".empty?
=> false
>> "".empty?
=> true

         Note the question mark at the end of the empty? method. This is a Ruby conventionindicating that the return value is boolean: true or false. Booleans are especially useful for control flow:




Booleans can also be combined using the && (‘‘and’’), || (‘‘or’’), and ! (‘‘not’’) operators:

Since everything in Ruby is an object, it follows that nil is an object, so it too can respond to methods. One example is the to_s method that can convert virtually any
object to a string: 

>> s
=> ""


This certainly appears to be an empty string, as we can verify by chaining the messages we pass to nil: 


We see here that the nil object doesn’t itself respond to the empty? method, but nil.to_s does.

               There’s a special method for testing for nil-ness, which you might be able to guess:

The code

puts "x is not empty" if !x.empty?

also shows an alternate use of the if keyword: Ruby allows you to write a statement that is evaluated only if the statement following if is true. There’s a complementary
unless keyword that works the same way: 

Neha  Jaggi

Skills    Ruby On Rails

Qualifications :- High School - , College/University - Graphic Era Hill University, Dehradun, College/University - ,
Location :-Dehradun,Dehradun,UTTARAKHAND,India

Experienced Software Developer with a demonstrated history of working in the Information Technology and services industry. Skilled in Web Technologies (Ruby on Rails, PostgreSQL, php, Laravel and AJAX). 


  Students (0)