From: Sam Stephenson Date: 2005-11-07T08:33:35+09:00 Subject: Lazy fun: Make unary minus silence stderr for backticks I was reading about mentalguy's lazy.rb and thought it'd be fun to use lazy evaluation as a vehicle for adding new syntactic sugar to Ruby. Here's one such example, which lets you prefix backticks with a unary minus to silence stderr: | % irb -r lazy_backtick | irb(main):001:0> `hello` | /opt/local/lib/ruby/1.8/irb/workspace.rb:81: command not found: hello | => "" | irb(main):002:0> -`hello` | => "" lazy_backtick.rb: | class LazyBacktick < String | instance_methods.each {|m| undef_method(m) unless m =~ /^__/} | | def initialize(command) | @command, @silence_stderr = command, false | end | | def -@ | @swallow_stderr = true | value | end | | def method_missing(method, *arguments, &block) | value.send(method, *arguments, &block) | end | | private | def value | @value ||= evaluate | end | | def evaluate | real_backtick "#@command#{' 2>/dev/null' if @silence_stderr}" | end | end | | module Kernel | alias_method :real_backtick, :'`' | | def `(command) | LazyBacktick.new(command) | end | end Note that I'm using the same approach as BlankSlate to remove LazyBacktick's methods, but inheriting from String instead -- this is so "String === `foo`" doesn't break. (It would be nice to have a mixin alternative to BlankSlate.) The way I'm silencing stderr is a bit, um, agile. Can it be made to work in Ruby on Windows without loading an external library (since open3 doesn't work there)? Sam