gpt4 book ai didi

php - Ruby 类实例变量与 PHP 属性

转载 作者:数据小太阳 更新时间:2023-10-29 09:01:57 27 4
gpt4 key购买 nike

在 php 中我可能有这样一个类:

class Item
public $quality = 10

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

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

我如何在 ruby​​ 中实现类似的功能?我有类似的东西:

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

我知道 Ruby 有实例变量和类变量。我试图在创建对象时在对象上定义一个实例变量。考虑到我可能会扩展类并且我希望继承或覆盖 quality 属性,做这样的事情的最佳做法是什么?

例如

class SuperItem < Item
@quality = 50
end

最佳答案

在初始化器中设置值。

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

关于php - Ruby 类实例变量与 PHP 属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33389946/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com