這(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'按預期工作。如果您將其添加爲答案,我會將其標記爲正確。 –