简体   繁体   中英

Ruby class instance variables vs php properties

In php I might have a class like so:

class Item
    public $quality = 10

    public function reduceQuality()
    {
        $this->quality -= 1;
    }
}

$item = new Item;
$item->reduceQuality();
print $item->quality; // outputs 9

How would I achieve similar in ruby? I have something like:

class Item

    attr_reader :quality

    @quality = 10

    def reduce_quality()
        @quality -= 1
    end
end

item = Item.new
item.reduce_quality # `reduce_quality': undefined method `-' for nil:NilClass (NoMethodError)
item.quality 

I understand Ruby has instance variables and class variables. I am trying to define an instance variable on the object when it's created. What's best practice to do something like this, bearing in mind I might extend the class and I want the quality property to be inherited or overridable?

eg

class SuperItem < Item
    @quality = 50
end

Set value in the initializer.

class Item

  attr_reader :quality

  def initialize
    @quality = default_quality
  end

  def reduce_quality
    @quality -= 1
  end

  def default_quality
    1
  end
end

class SuperItem < Item
  def default_quality
    50
  end
end

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM