Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 7021551
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 27, 20262026-05-27T23:27:56+00:00 2026-05-27T23:27:56+00:00

I have the following class called Tree that builds a simple tree class Tree

  • 0

I have the following class called Tree that builds a simple tree

class Tree
  attr_accessor :children, :node_name

  def initialize(name, children=[])
    @children = children
    @node_name = name
  end

  def visit_all(&block)
    visit &block
    children.each {|c| c.visit_all &block}
  end

  def visit(&block)
    block.call self

  end
end

ruby_tree = Tree.new("grandpa",
  [Tree.new("dad", [Tree.new("child1"), Tree.new("child2")]), 
    Tree.new("uncle", [Tree.new("child3"), Tree.new("child4")])])  
puts "Visiting a node"
ruby_tree.visit {|node| puts node.node_name}
puts

puts "visiting entire tree"
ruby_tree.visit_all {|node| puts node.node_name}

Now what I am trying to do is to be able to create a tree as nested hashes instead. For example, for this one this would be:

{‘grandpa’=>{‘dad’=>{‘child 1’=>{},’child 2’=>{}}, ‘uncle’=>{‘child 3’=>{}, ‘child 4’=>{}}}}

Any ideas that could help?

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-27T23:27:57+00:00Added an answer on May 27, 2026 at 11:27 pm

    It was melting my brain so I wrote a spec for it:

    # encoding: UTF-8
    
    require 'rspec' # testing/behaviour description framework
    require_relative "../tree.rb" # pull in the actual code
    
    # Everything in the `describe` block is rspec "tests"
    describe :to_h do
      # contexts are useful for describing what happens under certain conditions, in the first case, when there is only the top of the tree passed to to_h
      context "One level deep" do
        # a let is a way of declaring a variable in rspec (that keeps it useful)
        let(:ruby_tree) { Tree.new "grandpa" }
        let(:expected) { {"grandpa" => {} } }
        subject { ruby_tree.to_h } # this the behaviour you're testing
        it { should == expected } # it should equal what's in expected above
      end
      # The next two contexts are just testing deeper trees. I thought that each depth up to 3 should be tested, as past 3 levels it would be the same as 3.
      context "Two levels deep" do
        let(:ruby_tree) { 
          Tree.new( "grandpa", 
                      [Tree.new("dad"), Tree.new("uncle") ] 
                  )
        }
        let(:expected) do 
          {"grandpa" => { 
              "dad" => {}, "uncle" => {} 
            } 
          } 
        end
        subject { ruby_tree.to_h }
        it { should == expected }
      end
      context "grandchildren" do
        let(:ruby_tree){
          ruby_tree = Tree.new("grandpa",
          [Tree.new("dad", [Tree.new("child1"), Tree.new("child2")]), 
            Tree.new("uncle", [Tree.new("child3"), Tree.new("child4")])])
        }
        let(:expected) {
          {'grandpa'=>{'dad'=>{'child1'=>{},'child2'=>{}}, 'uncle'=>{'child3'=>{}, 'child4'=>{}}}}
        }
        subject { ruby_tree.to_h }
        it { should == expected }
      end
    end
    
    class Tree
      def to_h
        hash ={} # create a hash
        # `reduce` is a synonym for `inject`, see the other answer for a link to the docs,
        # but it's a type of fold 
        # http://en.wikipedia.org/wiki/Fold_(higher-order_function),
        # which will take a list of several objects and 
        # fold them into one (or fewer, but generally one) through application of a function. 
        # It reduces the list through injecting a function, hence the synonyms.
        # Here, the current node's list of children is folded into one hash by 
        # applying Hash#merge to each child (once the child has been been made 
        # into a one key hash, possibly with children too), and then assigned as 
        # the current node's hash value, with the node_name as the key.
        hash[@node_name] = children.reduce({}){|mem,c| mem.merge c.to_h}
        hash # return the hash
      end
    end
    

    I’m certain this could be done better, but it works at least.

    Btw, the hash you provided has some extra spaces in it that I don’t think should be there? e.g. “child 1” when it should be “child1”, unless you really want that added in?

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I have following code class User attr_accessor :name end u = User.new u.name =
I have one class called Holder (holder.cs) that contain the following: string name; List<String>
I have the following use case: There's a class called Template and with that
I have the following code in a static class called Methods that is archived
I have created UITableCellView class called NoteCell . The header defines the following: #import
Let's say you have a class called Customer, which contains the following fields: UserName
I have following simple class: @interface Article: NSObject { NSString *title; } @property (copy,
I have the following operator defined in a C++ class called StringProxy : operator
I have the following class hierachy: @interface Message : NSObject {} @end @implementation Message
In a class called 'Quality' I have the following constants defined: class Quality <

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.