【问题标题】:ruby - pipe-in from one class to anotherruby - 从一个类到另一个类
【发布时间】:2014-11-25 14:34:40
【问题描述】:

我有一个名为Foo 的类,它使用管道从命令行读取输入,并且运行良好。我有另一个名为Bar 的类,它调用Foo,并且必须以Foo 期望的相同方式输入(管道输入)Foo,但它似乎对我不起作用。

请参阅下面的我的 sn-p。 我将不胜感激。

注意: 我知道我可以通过将对象数据从Bar 传递到Foo 来避免这样做,但我想使用管道。

$ ls -x1
bar.rb
foo.rb
test.rb

$ cat *
# bar.rb
require "stringio"
class Bar
  def self.pipe
    input = StringIO.new
    input.write "bar"
    input.rewind
    $stdin = input
    Foo.print
    $stdin = STDIN
  end
end

# foo.rb
class Foo
  @@stdin = STDIN.tty? ? nil : $stdin.read #ok for cli pipe-in
  
  def self.print
    puts "stdin: #{@@stdin}"
  end
end

# test.rb
$:.unshift File.join(File.dirname(__FILE__))
require "foo"
require "bar"
Bar.pipe

$ echo "piped" | ruby test.rb 
stdin: piped

$ ruby test.rb 
stdin:

做错了什么,为什么?一个解决方案会很棒。

【问题讨论】:

    标签: ruby pipe


    【解决方案1】:

    我发现了我的错误。我将Foo 修改如下,但我破坏了它的功能。

    $ cat foo.rb 
    # foo.rb
    class Foo
      def self.print
        @@stdin = STDIN.tty? ? nil : $stdin.read #ok for cli pipe-in
        puts "stdin: #{@@stdin}"
      end
    end
    
    $ echo "piped" | ruby test.rb 
    stdin: bar
    

    【讨论】:

      猜你喜欢
      • 2017-10-19
      • 1970-01-01
      • 2016-06-11
      • 1970-01-01
      • 1970-01-01
      • 2011-08-26
      • 2021-06-25
      • 2013-05-18
      • 2010-11-15
      相关资源
      最近更新 更多