Download Ruby User's Guide - Contents & Chapters

Transcript
Ruby User's Guide - Accessors
change it. All we need to do is add a method named inspect. It should return a string that describes the
object in some sensible way, including the states of some or all of its instance variables.
Page 62 :
3/4
ruby> class Fruit
|
def inspect
|
"a fruit of the #{@kind} variety"
|
end
| end
nil
ruby> f2
"a fruit of the banana variety"
A related method is to_s (convert to string), which is used when printing an object. In general, you can
think of inspect as a tool for when you are writing and debugging programs, and to_s as a way of
refining program output. eval.rb uses inspect whenever it displays results. You can use the p method to
easily get debugging output from programs.
# These two lines are equivalent:
p anObject
puts anObject.inspect
Making accessors the easy way
Since many instance variables need accessor methods, Ruby provides convenient shortcuts for the standard
forms.
Shortcut
Effect
attr_reader :v
def v; @v; end
attr_writer :v
def v=(value); @v=value; end
attr_accessor :v
attr_reader :v; attr_writer :v
attr_accessor :v, :w attr_accessor :v; attr_accessor :w
Let's take advantage of this and add freshness information. First we ask for an automatically generated reader
and writer, and then we incorporate the new information into inspect:
ruby> class Fruit
|
attr_accessor :condition
|
def inspect
|
"a #{@condition} #{@kind}"
|
end
| end
nil
ruby> f2.condition = "ripe"
"ripe"
ruby> f2
"a ripe banana"
More fun with fruit
SteveHome Workstation
2006/10/29 下午 07:45