`
leonzhx
  • 浏览: 797098 次
  • 性别: Icon_minigender_1
  • 来自: 上海
社区版块
存档分类
最新评论

Classes, Objects, and Variables

阅读更多

1.      initialize is a special method in Ruby programs.When you call Class.new to create a new object, Ruby allocates some memory to hold an uninitialized object and then calls that object's initialize method, passing in any parameters that were passed to new . This gives you a chance to write code that sets up your object's state.


2.      @isbn is an instance variable, and the “at” sign is actually part of its name.


3.      The Float method takes its argument and converts it to a floating-point number, terminating the program with an error if that conversion fails.


4.      The p method prints out an internal representation of an object. Using it, we can see an object’s states ( instance variables).

 

5.      puts simply writes strings to your program’s standard output. When you pass it an object based on a class you wrote, it writes the name of the object’s class, followed by a colon and the object’s unique identifier (a hexadecimal number). It puts the whole lot inside #<...> . Ruby has a standard message, to_s , that it sends to any object it wants to render as a string. The puts method calls to_s in that object to get its string representation.

 

6.      Ruby provides a convenient shortcut. attr_reader creates these attribute reader methods for you:

class BookInStock

  attr_reader :isbn, :price

  def initialize(isbn, price)

    @isbn = isbn

    @price = Float(price)

  end

  # ..

end
 

   attr_reader creates the accessor methods, but the variables themselves don't need to be declared—they just pop into existence when you use them.

 

7.      When you want to set the value of an attribute for an object. You do that by creating a Ruby method whose name ends with an equals sign:

 

def price=(new_price)

  @price = new_price

end
 

 

8.      The assignment book.price = book.price * 0.75 invokes the method price= in the book object. If you create a method whose name ends with an equals sign, that name can appear on the left side of an assignment.

 

9.      If you want a write-only accessor, you can use the form attr_writer . If you want both a reader and a writer for a given attribute, so you can use attr_accessor method:

class BookInStock

  attr_reader :isbn

  attr_accessor :price

end
 

 

10.  floating-point numbers don’t always have an exact internal representation. When we multiply 33.8 by 100, we get 3379.99999999999954525265. The Integer method would truncate this to 3379. Adding 0.5 before calling Integer rounds up the floating-point value, ensuring we get the best integer representation.

 

11.  An attribute is just a method. Sometimes an attribute simply returns the value of an instance variable. Sometimes an attribute returns the result of a calculation. And sometimes those funky methods with equals signs at the end of their names are used to update the state of an object.

 

12.  Ruby comes with a good CSV library:

 

def read_in_csv_data(csv_file_name)

  books_in_stock = []

  CSV.foreach(csv_file_name, headers: true) do |row|

    books_in_stock << BookInStock.new(row["ISBN"], row["Amount"])
  
   end

 end
 

On the first line, we tell the CSV library to open the file with the given name. The

headers: true option tells the library to parse the first line of the file as the names of the columns. The library then reads the rest of the file, passing each row in turn to the block.

 

13.  Ruby has a couple of helper methods that let us load external files. We can use require to load in the Ruby library(such as CSV) and require_relative to load in ruby files in the same directory as the current file is.

 

14.  Ruby gives you three levels of protection:

a)        Public methods can be called by anyone—no access control is enforced. Methods are public by default (except for initialize , which is always private).

b)        Protected methods can be invoked only by objects of the defining class and its subclasses. Access is kept within the family.

c)        Private methods cannot be called with an explicit receiver—the receiver is always the current object, also known as self. This means that private methods can be called only in the context of the current object; you can’t invoke another object's private methods.

 

15.  Access control is determined dynamically, as the program runs, not statically. You will get an access violation only when the code attempts to execute the restricted method.

 

16.  If used with no arguments, the three functions set the default access control of subsequently defined methods:

class MyClass

  def method1 # default is 'public'

    #...

  end

  protected # subsequent methods will be 'protected'

  def method2 # will be 'protected'

    #...

  end

  private # subsequent methods will be 'private'

  def method3 # will be 'private'

    #...

  end

  public # subsequent methods will be 'public'

  def method4 # so this will be 'public'

    #...

  end

end
 

Alternatively, you can set access levels of named methods by listing them as arguments to the access control functions:

 

class MyClass

  def method1

  end

  def method2

  end

  # ... and so on

  public :method1, :method4

  protected :method2

  private :method3

end
 

 

17.  A variable is simply a reference to an object. Objects float around in a big pool somewhere (the heap, most of the time) and are pointed to by variables. The dup method of String , which creates a new string object with identical contents.

 

18.  You can prevent anyone from changing a particular object by freezing it (invoke the freeze method of the object). Attempt to alter a frozen object, and Ruby will raise a RuntimeError exception.

分享到:
评论

相关推荐

    Scala and Spark for Big Data Analytics.pdf

    Chapter 1, Introduction to Scala, will teach big data analytics using ... methods, classes, and objects in Scala; packages and package objects; traits and trait linearization; and Java interoperability.

    source insight 4086 破解版,

    Source Insight automatically shows references to functions, variables, classes, and more - almost instantly. Search across your project using advanced search features. Read More Code Analysis Source ...

    微软内部 C# 培训资料

    Create, name, and assign values to variables. Use common statements to implement flow control, looping, and exception handling. Create methods (functions and subroutines) that can return values and ...

    c++实验三、四.pdf

    The testing of the classes involves creating objects of the classes and calling their functions to perform operations. The testing data is provided for each class, including the circle, rectangle, and...

    Objective-C for Absolute Beginners: iPhone and Mac Programming Made Easy

    - **Classes and Objects:** OOP revolves around the concept of objects, which are instances of classes. Classes define the structure and behavior of objects. You'll learn how to define classes, create ...

    Object Pascal Handbook,最新Ddelphi书籍,for XE7

    Chapter 2: Variables and Data Types Chapter 3: Language Statements Chapter 4: Procedures and Functions Chapter 5: Arrays and Records Chapter 6: All About Strings Part II Chapter 7: Objects Chapter 8:...

    Objective-C编程(第4版)

    3 Classes, Objects, and Methods 27 4 Data Types and Expressions 51 5 Program Looping 71 6 Making Decisions 93 7 More on Classes 127 8 Inheritance 151 9 Polymorphism, Dynamic Typing, and Dynamic ...

    Programming Excel With Vba And .net.chm

    Classes and Modules Section 2.3. Procedures Section 2.4. Variables Section 2.5. Conditional Statements Section 2.6. Loops Section 2.7. Expressions Section 2.8. Exceptions Section 2.9. ...

    Objective-C for Absolute Beginners iPhone, iPad, and Mac Programming Made Easy

    - **Objective-C Classes, Objects, and Methods**: Provides a detailed look at how to define and use classes, objects, and methods in Objective-C. - **Diving into Objective-C**: Explores more advanced ...

    C 程序设计教学课件:Chapter 3 class and object.ppt

    Chapter 3 of the C++ programming course delves into the fundamental concepts of object-oriented programming, specifically focusing on classes and objects. Object-oriented programming (OOP) is a ...

    Programming in Objective-C, 第四版,ePub格式

    3 Classes, Objects, and Methods 4 Data Types and Expressions 5 Program Looping 6 Making Decisions 7 More on Classes 8 Inheritance 9 Polymorphism, Dynamic Typing, and Dynamic Binding 10 More on ...

    Programming in Objective-C Fourth Edition (2011)

    3 Classes, Objects, and Methods  4 Data Types and Expressions  5 Program Looping  6 Making Decisions  7 More on Classes  8 Inheritance  9 Polymorphism, Dynamic Typing, and Dynamic Binding...

    Perl To Python Migration

    The first section of Perl to Python Programming will show you the basic layout and approach of the two languages whilst the second ...differences of using Python data types and objects over Perl variables....

    Data Manipulation with R(PACKT,2ed,2015)

    We then discuss the mode of R objects and its classes and then highlight different R data types with their basic operations. The primary focus on group-wise data manipulation with the split-apply-...

    Prentice.Hall.C++.for.Business.Programming.2nd.Edition.2005.chm

    The string Class: An Introduction to Classes and Objects 426 Section 10.1. Objects, Classes, and Object-Oriented Systems 427 Section 10.2. Introduction to string Objects 430 Section 10.3. ...

    Learning.Scala.Practical.Functional.Programming.for.the.JVM

    Why learn Scala? You don’t need to be a data scientist or distributed computing expert to appreciate this ... Objects, Case Classes and Traits Chapter 10. Advanced Typing Appendix A. Reserved Words

Global site tag (gtag.js) - Google Analytics