2013-04-03 72 views
0

在Ruby中,我想向用戶顯示一個實例變量的值,然後詢問應該使用的值是什麼gets.chomp。因爲我會爲幾個變量做這個,所以我想用一個方法來檢查這個值。我的困難是,當我在方法中調用gets時,程序運行時不會詢問用戶輸入。獲取不在Ruby方法中調用

這裏是代碼的相關部分:

class TagPodcast 

    # ... Code to pull ID3v2 tags from MP3 file 

    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 

TagPodcast.new("myfile.mp3").inspect_tags 

當我運行程序時,它打印Title: My Title Here但隨後退出時不要求輸入。我需要做什麼才能撥打gets

+1

這無關你的'gets'的問題,但它現在代表'set_tag'不會設置任何東西我懷疑你想在最後做一些類似'self.tag = tag'或'@tag = tag'的東西(除非這是僞代碼)。 –

+3

您是否嘗試過使用STDIN.gets.chomp或$ stdin.gets.chomp來確保您從預期來源獲得輸入? http://stackoverflow.com/a/12041600/1286639 – GoZoner

+0

@GoZoner:使用'STDIN.gets.chomp'按預期工作。如果您將其添加爲答案,我會將其標記爲正確。 –

回答

0

確保你正在輸入用從標準輸入:

STDIN.gets.chomp 

$stdin.gets.chomp 
2

這(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不是你期望它在執行時所期望的。

+0

感謝這個使用'instance_variable_set'工程就像一個魅力@GoZoner和@ Effbot在上面的評論中指出,問題是使用'ARGV'改變了STDIN。 –

+0

不客氣,謝謝你的更新,很高興知道這個問題!在某些時候可能發生在我們所有人身上...... –