Assigning STDERR to a variable in Ruby
The following lists a few ways to assign STDERR streams to variables in Ruby:
- $ 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.
- $ 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:
- >> 0.fib
- => 0
- >> 1.fib
- => 1
- >> 29.fib
- => 514229
- class Integer
- def fib
- return 0 if self == 0
- return 1 if self <= 2
- (self - 2).times.inject([1, 1]) { |memo, value| memo = [memo.last, (memo.first + memo.last)] }.last
- end
- end
The standard recursive answer will usually suffice in an interview:
- class Integer
- def fib
- return self if self < 2
- (self - 2).fib + (self - 1).fib
- end
- 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:
- class Foo
- def self.public
- "public"
- end
- private
- def self.private
- "private"
- end
- end
- > Foo.public #=> "public"
- > Foo.private #=> "private"
One would expect a NoMethodError when calling private on class Foo, but that isn’t the case. However:
- class Bar
- # define methods under Bar's Metaclass
- class << self
- def public
- "publc"
- end
- private
- def private
- "private"
- end
- end
- end
- > Bar.public #=> "public"
- > Bar.private #=> NoMethodError: private method `private' called for Bar:Class
- > Bar.send(:private) #=> "private"
Posted on Feb 02, 2011 | filed under Ruby | 5 comments
