From: Robert Klemme Date: 2011-05-03T16:30:21+09:00 Subject: Re: Help making a method more concise On Tue, May 3, 2011 at 6:28 AM, Christopher Dicely wrote: > On Mon, May 2, 2011 at 11:17 AM, Mark Hayes wrote: >> Hello, >> >> I'm looking to improve my skills as a Rubyist and would like to know if the >> "depth" method could be expressed more precisely.  Any help would be greatly >> appreciated, thanks! >> >> require 'test/unit' >> >> class Node >>  attr_accessor :value, :lchild, :rchild >> >>  def depth >>    [lchild ? lchild.depth : 0, rchild ? rchild.depth : 0].max + 1 >>  end >> end > > > def depth >  1 + [lchild,rchild].map {|ch| [ch}.max > end Does not work: apart from the syntax invocation of #depth is missing. If we add that we have a solution that has been proposed already. > or even: > > def depth >   1 + [lchild,rchild].map(&:to_i).max > end > > alias to_i depth Now that's an interesting idea to use the knowledge that nil.to_i => 0! > or: > > add empty (no value) left & right children when you first add a value > to a node, and: > > def empty? >  @value.nil? > end > > def depth >  empty? ? 0 : [lchild,rchild].map(&:depth).max > end I don't think this captures the original semantics properly. Now there are only two states: empty, not empty. But the original design allowed for more states: empty, left set, right set, both set. Even if not for #depth this is likely important for other tree algorithms. Kind regards robert -- remember.guy do |as, often| as.you_can - without end http://blog.rubybestpractices.com/