Ruby On Rails Classroom image

Anil  Bist / 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: 

>> nil.to 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: 

 
 
 
image
Anil  Bist

Skills    Ruby On Rails

Qualifications :- High School - SLV, College/University - Graphic Era Deemed Univ University,
Location :-Dehradun,Dehradun,Uttarakhand,India
Description:-

I started my Professional Journey in 2006 with one of the Web Development Company in Bangalore and my 1st framework was "Ruby on Rail" as Web development and delivered around 5+ Projects using this platform. Then came another dimension as JEE/Sturst framework, Gradually I realized that I want to build something on my own and give my passion and energy on creating something different a
Explore

 

  Students (0)