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 01, 2011 | filed under Ruby | 5 comments
