Classes, Objects, and Variables_Ruby_编程开发_程序员俱乐部

中国优秀的程序员网站程序员频道CXYCLUB技术地图
热搜:
更多>>
 
您所在的位置: 程序员俱乐部 > 编程开发 > Ruby > Classes, Objects, and Variables

Classes, Objects, and Variables

 2012/8/21 11:11:11  leonzhx  程序员俱乐部  我要评论(0)
  • 摘要:1.initializeisaspecialmethodinRubyprograms.WhenyoucallClass.newtocreateanewobject,Rubyallocatessomememorytoholdanuninitializedobjectandthencallsthatobject'sinitializemethod,passinginanyparametersthatwerepassedtonew
  • 标签:RIA

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.

发表评论
用户名: 匿名