Ruby On Rails Classroom image

Pooja  Negi / Student / Web Technology

To post your Question Join Classroom
Lesson Topics's No:-  ||
Lessons:-Ruby Classes-Constructors

  Ruby Classes

We’ve said before that everything in Ruby is an object, and in this section we’ll finally get to define some of our own. Ruby, like many object-oriented languages, uses classes to organize methods; these classes are then instantiated to create objects. If you’re new to object-oriented programming, this may sound like gibberish, so let’s look at some concrete examples


We’ve seen lots of examples of using classes to instantiate objects, but we have yet to do so explicitly. For example, we instantiated a string using the double quote characters, which is a literal constructor for strings:


>> s =  "foobar"                # A literal constructor for strings using double quotes
=> "foobar"
>> s.class
=> String


We see here that strings respond to the method class and simply return the class they belong to.

          Instead of using a literal constructor, we can use the equivalent named constructor, which involves calling the new method on the class name:10 


>> s =  String .new  ("foobar")     # A named constructor for a string
=> "foobar"
>> s.class
=> String
>> s ==   "foobar"
=> true


This is equivalent to the literal constructor, but it’s more explicit about what we’re doing.
            Arrays work the same way as strings: 

>> a =  Array  .new  ([1, 3, 2])
=> [1, 3, 2]


 Hashes, in contrast, are different. While the array constructor takes an initial value for the array, takes a default value for the hash, which is the
value of the hash for a nonexistent key:


>> h =  Hash .new
=> {}
>> h  [:foo]                                               # Try to access the value for the nonexistent key :foo.
=> nil
>> h =  Hash .new(0)                                 # Arrange for nonexistent keys to return 0 instead of nil.
=> {}
>> h [:foo]
=> 0


When a method gets called on the class itself, as in the case of new, it’s called a class method. The result of calling new on a class is an object of that class, also called
an instance of the class. A method called on an instance, such as length, is called an instance method.

Pooja   Negi

Skills    Ruby On Rails

Qualifications :- High School - SSN high school, College/University - HNBGU, College/University - SRHU,
Location :-Ranipokhari,Rishikesh,Uttarakhand,India
Description:- Student

  Students (0)