这(sligtly修订)计划要求我输入如预期(只是增加了访问和构造函数):
class TagPodcast
attr_accessor :title
def initialize(filename)
@filename = filename
end
def inspect_tags
puts "Title: " + @title
set_tag(self.title)
end
def set_tag(tag)
new_value = gets.chomp
tag = new_value unless new_value == ""
end
end
tp = TagPodcast.new("myfile.mp3")
tp.title = 'Dummy Title'
tp.inspect_tags
你的代码有一个不同的问题,但。变量是按值传递给方法,而不是引用,所以预期此代码将不会表现:
class Foo
attr_accessor :variable
def set_var(var)
var = 'new value'
end
def bar
self.variable = 'old value'
set_var(self.variable)
puts "@variable is now #{self.variable}"
end
end
Foo.new.bar
这将打印@variable is now old value
。我可以想到两种解决方法。任一组的实例变量的方法外,象这样:
class Foo
attr_accessor :variable
def do_stuff
'new value'
end
def bar
self.variable = 'old value'
self.variable = do_stuff
puts "@variable is now #{self.variable}"
end
end
Foo.new.bar
,或者使用Ruby的强大元编程功能和杠杆instance_variable_set
通过传递它的名字作为一个符号动态地设置一个实例变量:
class Foo
attr_accessor :variable
def set_var(var)
instance_variable_set var, 'new value'
end
def bar
self.variable = 'old value'
set_var(:@variable)
puts "@variable is now #{self.variable}"
end
end
Foo.new.bar
至于您的原始问题,我们需要更多地了解执行上下文。可能STDIN不是你期望它在执行时所期望的。
这无关你的'gets'的问题,但它现在代表'set_tag'不会设置任何东西我怀疑你想在最后做一些类似'self.tag = tag'或'@tag = tag'的东西(除非这是伪代码)。 –
您是否尝试过使用STDIN.gets.chomp或$ stdin.gets.chomp来确保您从预期来源获得输入? http://stackoverflow.com/a/12041600/1286639 – GoZoner
@GoZoner:使用'STDIN.gets.chomp'按预期工作。如果您将其添加为答案,我会将其标记为正确。 –