[Ruby笔记]15.@instance_variable 以及 糖“在方法名中可使用=”

代码

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
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值