Ruby On Rails Classroom image

Pooja  Negi / Student / Web Technology

To post your Question Join Classroom
Lesson Topics's No:-  |1 | 2|Last
Lessons:-Modifying Built-in Classes -A Controller Class

Modifying Built-in Classes

While inheritance is a powerful idea, in the case of palindromes it might be even more natural to add the palindrome? method to the String class itself, so that (among other things) we can call palindrome? on a string literal, which we currently can’t do:


>>  "level"  .palindrome?
 NoMethodError:  undefined  method  `palindrome?'  fo r "level":String


Somewhat amazingly, Ruby lets you do just this; Ruby classes can be opened and modified, allowing ordinary mortals such as ourselves to add methods to them:12 


>>  class   String
>>  # Returns  true  if  the  string   is its  own  reverse.
>> def  palindrome?
>>  self == self. reverse
>>  end
>>  end
=>  nil
>>  "deified"  .palindrome?
=>  true


     (I don’t know which is cooler: that Ruby lets you add methods to built-in classes or that "deified" is a palindrome.)  

Modifying built-in classes is a powerful technique, but with great power comes great responsibility, and it’s considered bad form to add methods to built-in classes without having a really good reason for doing so. Rails does have some good reasons; for example, in web applications we often want to prevent variables from being blank—e.g., a user’s name should be something other than spaces and other whitespace—so Rails adds a blank? method to Ruby. Since the Rails console automatically includes the Rails extensions, we can see an example here (this won’t work in plain irb):


>>   ""  .blank?
=>   true
>>   "    "  .empty?
=>   false
>>   "    "  .blank?
=>   true
>>  nil  .blank?
=>  true


We see that a string of spaces is not empty, but it is blank. Note also that nil is blank; since nil isn’t a string, this is a hint that Rails actually adds blank? to String’s base class, which (as we saw at the beginning of this section) is Object itself. We’ll see some other examples of Rails additions to Ruby classes in Section 8.2.1.

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)