ruby 类 - attr_accessor

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了ruby 类 - attr_accessor相关的知识,希望对你有一定的参考价值。

# Delete the Getter and Setter from above, replace it with attr_accessor
# Note: Doesn't write your initialize method instance variables!
class Product
  attr_accessor :description
 
 
  # Always Initialize It First
  def initialize( description, price)
    @id = rand(100...999)
    @description = description
    @price = price
  end
 
  
  def to_s
    # return by rewriting to_s :-p and add tabs with \t
    return "#{@id}\t#{@description}\t#{@price}"
  end
end
 
# Set it up... Instantiate our class
book = Product.new( "Ruby On Rails For Web Development", 26.95 )
book2 = Product.new( "Intro To Ruby", 25.95 )
 
# Call the thing!
puts book
puts book2
 
# Call The Description Getter
puts book.description
# Call the Setter, set a different Description
puts book.description= "I Like Cheese!"

以上是关于ruby 类 - attr_accessor的主要内容,如果未能解决你的问题,请参考以下文章

ruby 类 - attr_accessor

Ruby的attr_accessor如何产生类变量或类实例变量而不是实例变量?

扩充类

这行 Ruby 代码在做啥? [复制]

晕菜了,Ruby类中的变量!

为啥 Ruby setter 需要“自我”。班级内的资格?