Skip to main content

Scope and Access modifiers in Ruby


Access modifiers (or access specifiers) are keywords in object-oriented languages that set the accessibility of classes, methods, and other members.

Access modifiers set the visibility of methods and member fields. Ruby has three access modifiers: public, protected and private. In Ruby, all data members are private. Access modifiers can be used only on methods. Ruby methods are public, unless we say otherwise. The scope of the methods is until another scope comes i.e. when we write private all the methods below it are private until any other scope (i.e. protected or public).

NOTE: Ruby does not apply any access control over instance and class variables.

Public Methods: Public methods can be called by anyone. Methods are public by default except for initialize, which is always private.

Private Methods: Private methods cannot be accessed, or even viewed from outside the class. Only the class methods can access private members.

Protected Methods: A protected method can be invoked only by objects of the defining class and its subclasses. Access is kept within the family.

  • The public methods can be accessed from inside the definition of the class as well as from the outside of the class.
  • The difference between the protected and the private methods is subtle. Neither can be accessed outside the definition of the class.
  • They can be accessed only within the class itself and by inherited or parent classes.

Example:

# define a class
class Box
# constructor method
def initialize(w,h)
 @width, @height = w, h
end

# instance method by default it is public
def getArea
 getWidth * getHeight
end

# define private accessor methods
private

def getWidth
 @width
end

def getHeight
 @height
end

protected

def printArea
 @area = getWidth * getHeight
 puts "Big box area is : #@area"
end
end

# create an object
box = Box.new(10, 20)

# call instance methods
a = box.getArea
puts "Area of the box is : #{a}"

#try to call private methods
w = box.getWidth

puts "Width of the box is : #{w}"

# try to call protected or methods
box.printArea

OUTPUT:

Area of the box is : 200

access_modifiers.rb:39:in `<main>': private method `getWidth' called for #<Box:0x93ee654 @width=10, @height=20> (NoMethodError)


References:





Comments

Popular posts from this blog

List of Common mistakes in Ruby

Always use spaces around operators, after commas, colons and semicolons, around { and before }. White space might be (mostly) irrelevant to the Ruby interpreter, but its proper use is the key to writing easily readable code. Also it makes the design more readable and code much cleaner.
product = 1 * 2 array = [1, 2, 3, 4, 5] array.map { |a| a + 2 }

There should be no spaces after (, [ or before ], ) these brackets.
['ankur', 'vyas'] sum(a, b)
Also don't use spaces in while providing the range.
Use5..9 over 5 .. 9Use'a'..'z' over 'a' .. 'z'
When using switch case statements use the following indentation.
casewhen input = '+'puts'The operation is addition'when'-'puts'The operation is subtraction'when'*'puts'The operation is multiplication'elseputs'The operation is division'end
Use following indentation if the parameters exceeds to more than one line.
defsend_mail(source) Mailer.deliver(…

5 Useful Android Apps

There are many apps available for Android but these are some useful apps which I use regularly.
1. Money View: Financial Planning
Description: With the Free Money View app, you get a real-time visibility into your entire Personal Finances. It works by itself without any manual data entry - their daily expense manager app organizes our financial summary by analyzing SMS sent by our bank and billers to our phone. The app auto-tracks your expense, bills and account balances across all our financial accounts to help us stay on top of our money. The app is highly secure as it never reads any sensitive data - no full bank account numbers, no OTP, and no Netbanking login/password.
As it anaylzes the money transactions via the SMS in our phone it is highly useful app for tracking our expenses, so we can know our money is going in which direction so we can control it.




More information:  https://play.google.com/store/apps/details?id=com.whizdm.moneyview&hl=en

2. Any.do To-do List | Task List
Descr…

OOP Polymorphism

Definition: "Poly" stands for "many" and "morph" stands for "forms". Generally, polymorphism means one name different uses. Technically, it means being able to send the same message to different objects and get different result.
Polymorphism through Inheritance
We can achieve polymorphism through inheritance. For example
classGenericParser defparseraiseNotImplementedError, 'You must implement the parse method'endendclassJsonParser < GenericParserdefparseputs'An instance of the JsonParser class received the parse message'endendclassXmlParser < GenericParserdefparseputs'An instance of the XmlParser class received the parse message'endendHere the GenericParser is the base class. Class JsonParser and XmlParser are inherited from the GenericParser.
Now suppose we run the below code.
puts'Using the XmlParser' parser = XmlParser.new parser.parse puts'Using the JsonParser' parser = JsonParser.new parser.parseThe o…