Learning Ruby 2 Classes, Objects, and Variables

with <Programming Ruby 2nd>
Chapter 3
Classes, Objects, and Variables
Class
class Song
  def initialize(name, artist, duration)
    @name     = name
    @artist   = artist
    @duration = duration
  end
end
initialize, which is always private
Instance variables are accessible to all the methods in an object, and each object has its own copy of its instance variables.

song.inspect → #<Song:0x1c7ca8 @name="Bicylops", @duration=260,
               @artist="Fleck">

In Ruby, classes are never closed.
class Song
  def to_s
    "Song: #@name–#@artist (#@duration)"
  end
end

Inheritance and Messages
class KaraokeSong < Song
      def initialize(name, artist, duration, lyrics)
        super(name, artist, duration)
        @lyrics = lyrics
      end
   
    def to_s
          super + " [#@lyrics]"
    end
end

If you don’t specify a parent when de?ning a class, Ruby supplies class Object as a default.

Ruby classes can include the functionality of any number of mixins (a mixin is like a partial class de?nition). This provides a controlled multiple-inheritance-like capability
with none of the drawbacks.

Objects and Attributes
class Song
  def name
    @name
  end
  def artist
    @artist
  end
  def duration
    @duration
  end
end

convenient shortcut:
class Song
  attr_reader :name, :artist, :duration
end
Symbol object — You can think of :artist as meaning the name of the variable artist, and plain artist as meaning the value of the variable.

Writable Attributes
class Song
  def duration=(new_duration)
    @duration = new_duration
  end
end
shortcut:
class Song
  attr_writer :duration
end

Virtual Attributes
class Song
  def duration_in_minutes
    @duration/60.0   # force floating point
  end
  def duration_in_minutes=(new_duration)
    @duration = (new_duration*60).to_i
  end
end
To the outside world, duration_in_minutes seems to be an attribute like any other. Internally, though, it has no corresponding instance variable.

Attributes, Instance Variables, and Methods
An attribute is just a method.
The internal state is held in instance variables. The external state is exposed through methods we’re calling attributes. And the other actions your class can perform are just regular methods.

Class Variables
A class variable is shared among all objects of a class.
class variables must be initialized before they are used.
class Song
  @@plays = 0
  def initialize(name, artist, duration)
    @name     = name
    @artist   = artist
    @duration = duration
    @plays    =0
  end
  def play
    @plays += 1   # same as @plays = @plays + 1
    @@plays += 1
    "This song: #@plays plays. Total #@@plays plays."
  end
end

Class Methods
class Example
  def instance_method      # instance method
  end
  def Example.class_method # class method
  end
end

class SongList
  MAX_TIME = 5*60           #  5 minutes
  def SongList.is_too_long(song)
    return song.duration > MAX_TIME
  end
end

Class Method De?nitions
class Demo
  def Demo.meth1
    # …
  end
  def self.meth2
    # …
  end
  class <<self
    def meth3
      # …
    end
  end
end

Singletons and Other Constructors
class MyLogger
  private_class_method :new #making MyLogger’s new method private
  @@logger = nil
  def MyLogger.create #provide a class method
    @@logger = new unless @@logger
    @@logger
  end
end

Access Control
• Public methods
• Protected methods
• Private methods
If a method is protected, it may be called by any instance of the de?ning class or its subclasses. If a method is private, it may be called only within the context of the calling object—it is never possible to access another object’s private methods directly, even if the object is of the same class as the caller.

Specifying Access Control
private         # subsequent methods will be 'private'
    def method3
      #…
    end
#….

or

class MyClass
  def method1
  end
  # … and so on
  public    :method1, :method4
  protected :method2
  private   :method3
end

class Account
  attr_reader :balance # accessor method 'balance'
  protected :balance   # and make it protected

Variables
person1 = "Tim"
person2 = person1
person1[0] = 'J'
person1       "Jim"
          →
person2       "Jim"
          →
variable isn't an object
variables hold references to objects, not the objects themselves.

you could avoid aliasing by using the dup method of String, which creates a new String object with identical contents.
    person1 = "Tim"
    person2 = person1.dup
    person1[0] = "J"
    person1   → "Jim"
    person2   → "Tim"
You can also prevent anyone from changing a particular object by freezing it

轉載請註明: 轉自船長日誌, 本文鏈接地址: http://www.cslog.cn/Content/learning_ruby_2/zh-hant/

此條目發表在 Ruby on Rails 分類目錄。將固定鏈接加入收藏夾。

發表評論