代码
Sugar Class
写一个Sugar
类,方法 price=(amount)
可以设置价格,方法price
可以获取价格 :
class Sugar
def price=(amount)
@price = amount
end
def price
@price
end
end
Instance variable
变量 @price
就是 Instance variable,可以看到其实不需要把@price
写到整个Class
的顶部它就可以被这个Sugar
类的所有方法共享了,同时我也没有写initialize
.
运行
打开irb
,可以放在同一个目录下直接require
进来,这里方便看 :
PS C:\Users\Administrator> irb --simple-prompt
>> class Sugar
>> def price=(amount)
>> @price = amount
>> end
>> def price
>> @price
>> end
>> end
=> :price
# 创建对象
>> sugar = Sugar.new
=> #<Sugar:0x00000002a63a18>
# 设置价格
>> sugar.price = 100.00
=> 100.0
# 获取价格
>> sugar.price
=> 100.0
糖
- Ruby不仅允许在方法(method)命名里使用
=
,还可以在使用sugar.price = 100.00
这种写法时,自动忽略=
之前的空格; sugar.price = 100.00
本质是方法调用sugar.price=(100.00)
;
引用
《The Well-Grounded Rubyist, Second Edition》
(https://www.manning.com/books/the-well-grounded-rubyist-second-edition)
3.3. Setter methods
∵) ―(太陽)―
∵∵)/ ┃ \
∵∵∵)
∵∵∵∵) V
∵∵∵) ◇|◇
∵∵)/■\
┃(´∪`)♪
┃[のほほん]
┃ ∪ ∪
http://emoji.vis.ne.jp/nohohon6.htm