4.使用对象属性

使用对象属性

知识点

  • attr_accessor:定义可存取对象的属性

attr_accessor

提供了可供对象外部使用的属性。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
class Game
attr_accessor :price #, :title
def initialize(title = "怪物猎人世界", price = 200)
@title = title
@price = price
end
def show()
puts "标题: #{@title}"
puts "价格: #{@price}"
end
end

mygame = Game.new()
mygame.show()

puts "title is " + mygame.respond_to?("title").to_s
puts "price is " + mygame.respond_to?("price").to_s

#mygame.title = "Super Mario World"
mygame.price = 150
mygame.show()