2013-04-03 38 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

不客气,谢谢你的更新,很高兴知道这个问题!在某些时候可能发生在我们所有人身上...... –