Project

General

Profile

Actions

Feature #5550

closed

Hash#depth, Hash#flat_length for recursive hashes

Feature #5550: Hash#depth, Hash#flat_length for recursive hashes

Added by sawa (Tsuyoshi Sawada) almost 14 years ago. Updated almost 13 years ago.

Status:
Rejected
Assignee:
-
Target version:
-
[ruby-dev:44776]

Description

I often have a hash whose value is recursively a hash, which may look like the following:

{"Japan" =>
    {"Hokkaido" => "Sapporo", ...},
    {"Honhuu" =>
        {"Aomori" => "Hirosaki", ...},
        {"Akita" => ...},
        ...
    },
    {"Shikoku" => ...},
    ...
}

In these cases, it will be convenient if there is a way to know the (maximum) depth of he original hash, and the numbers of all the "terminal nodes". I would like to propose two methods Hash#depth and Hash#flat_length, whose Ruby implementation can be as follows:

class Hash
def depth
	1 + (values.map{|v| Hash === v ? v.depth : 1}.max)
end
def flat_length
	values.inject(0){|sum, v| sum + (Hash === v ? v.flat_length : 1)}
end
end

Updated by matz (Yukihiro Matsumoto) almost 14 years ago Actions #1 [ruby-dev:44794]

  • Status changed from Open to Feedback

Hashの本質はkey-valueのマッピングなので、valueが再帰的にHashであることを想定した(再帰的なHashでなければ役に立たない)メソッドを追加することには抵抗があります。
わずか6行のmonkey patchingを避けるためにすべてのRubyに追加すべきメソッドですか?

Updated by alexeymuranov (Alexey Muranov) almost 14 years ago Actions #2 [ruby-dev:44799]

Excuse me, can you be more precise with your example please? Ruby does not accept it (after removing the dots "..."). Are you talking about nested hashes? How about creating a class Tree that would inherit from Hash and define additional methods there?

Updated by trans (Thomas Sawyer) almost 14 years ago Actions #3 [ruby-dev:44807]

I take it you meant nested hash. I think your methods will infinite loop on recursive hash --and that needs to be considered.

I understand #depth, Array might use such a method too. But #flat_length, I don't quite get what is being counted.

Updated by mame (Yusuke Endoh) almost 13 years ago Actions #4 [ruby-dev:46555]

  • Status changed from Feedback to Rejected

No feedback, looks hopeless to me. Closing.

--
Yusuke Endoh

Actions

Also available in: PDF Atom