Assigning STDERR to a variable in Ruby

The following lists a few ways to assign STDERR streams to variables in Ruby:

  1. $ result = %x[find . -name ruby -type f 2>&1]

assigns both STDERR and STDOUT to result. This might be useful, for example, when you want to capture the entire output of the command.

  1. $ result = %x[find . -name ruby -type f 2>&1 1>/dev/null]

redirects STDERR to STDOUT which will assign it to result and then discards the command’s STDOUT. This might be useful when you only care to capture any error generated by the command.

The examples above use the %x operator to run the commands. You also might find useful this summary of 6 Ways To Run Shell Commands In Ruby.

Posted on Mar 24, 2011 | filed under Ruby | 0 comments


Using Ruby's inject to calculate a fibonacci number

Another twist to a common interview question. This time we’ll extend Ruby’s Integer base class so that we can do something like this:

  1. >> 0.fib
  2. => 0
  3. >> 1.fib
  4. => 1
  5. >> 29.fib
  6. => 514229


  1. class Integer
  2.  
  3. def fib
  4. return 0 if self == 0
  5. return 1 if self <= 2
  6. (self - 2).times.inject([1, 1]) { |memo, value| memo = [memo.last, (memo.first + memo.last)] }.last
  7. end
  8. end

The standard recursive answer will usually suffice in an interview:

  1. class Integer
  2.  
  3. def fib
  4. return self if self < 2
  5. (self - 2).fib + (self - 1).fib
  6. end
  7.  
  8. end

I’d just expect the candidate to be aware of the limitations of this approach. I like to pose this question during an interview.

Posted on Feb 11, 2011 | filed under Ruby | 0 comments


Setting a private class method in Ruby

In order to set the visibility on a class method in Ruby, you have to set it under the class’ Metaclass. Here’s an example:

  1. class Foo
  2. def self.public
  3. "public"
  4. end
  5.  
  6. private
  7.  
  8. def self.private
  9. "private"
  10. end
  11. end
  1. > Foo.public #=> "public"
  2. > Foo.private #=> "private"

One would expect a NoMethodError when calling private on class Foo, but that isn’t the case. However:

  1. class Bar
  2. # define methods under Bar's Metaclass
  3. class << self
  4. def public
  5. "publc"
  6. end
  7.  
  8. private
  9.  
  10. def private
  11. "private"
  12. end
  13. end
  14. end
  1. > Bar.public #=> "public"
  2. > Bar.private #=> NoMethodError: private method `private' called for Bar:Class
  3. > Bar.send(:private) #=> "private"

Posted on Feb 02, 2011 | filed under Ruby | 5 comments