改变:
def initialize(showName)
:name = showName
end
至
def initialize(showName)
@name = showName
end
你也可以这样做:
attr_accessor :name, :tvdbID
一些例子:
class Dog
def initialize(name)
@name = name
end
def show
puts "I am a Dog named: " + @name
end
def add_last_name(last_name)
@name = @name + " " + last_name
end
end
d = Dog.new "Fred"
d.show
d.add_last_name("Rover")
d.show
--output:--
I am a Dog named: Fred
I am a Dog named: Fred Rover
所以实例变量可以从类中自由访问。但是,您不能从类外部访问上例中的实例变量:
d = Dog.new "Fred"
puts d.name
--output:--
1.rb:17:in `<main>': undefined method `name' for #<Dog:0x000001010a5b48 @name="Fred"> (NoMethodError)
以下是从类外部访问实例变量的方法:
class Dog
def initialize(name)
@name = name
end
def name #getter
@name
end
def name=(val) #setter
@name = val
end
end
d = Dog.new "Fred"
puts d.name
--output:--
Fred
那些 getter 和 setter 很难输入——尤其是如果你有 10 个实例变量——所以 ruby 提供了一个快捷方式:
class Dog
def initialize(name, age)
@name = name
@age = age
end
attr_accessor :name, :age
end
d = Dog.new("Fred", 5)
puts d.name
puts d.age
d.age = 6 #calls age=() method
puts d.age
--output:--
Fred
5
6
但是习惯上在类的开头写 attr_accessor 行。