I want to know how Ruby can rearrange the array.

Asked 2 years ago, Updated 2 years ago, 40 views

I don't know the code in split that would be a two-dimensional array of result.
Do not use the library.

[
  {
    :type=>"h1",:value=>1,
    :children=>[{:type=>"p",:value=>2}]
  },
  {
    :type=>"h2",:value=>3,
    :children=>[
      {
        :type=>"p",:value=>4,
        :children=>[
          {:type=>"p",:value=>5},
          {:type=>"h3",:value=>6}
        ],
      },
      {:type=>"p",:value=>7},
      {
        :type=>"h3",:value=>8,
        :children=>[{:type=>"h3",:value=>9}]
      }
    ]
  },
  {
    :type=>"h2",:value=>11,
    :children=>[{:type=>"p",:value=>10}]
  }
]

def split(obj)
  # Please this code
end

# result
[
  ["h1:1", "p:2",]
  ["h2:3", "p:4", "p:5",]
  ["h3:6", "p:7"],
  ["h3:8"],
  ["h3:9"],
  ["h2:11", "p:10",
]

ruby

2022-09-30 19:34

1 Answers

It's not very smart, but...

Use recursion to retrieve data, then use flatten to make it one-dimensional, put elements containing h to elements containing h in one array (ary2) and copy ay2 to ay3 when ay2 moves on.
I'm destroying the structure, so (Mr. Nekketsuuu♦ wrote it, and personally, I don't think it's a hash?) I don't know if you really want it, but just for your information.

def split(obj)
  b=extract(obj)
  union(b)
end

def extract(obj)
  aary = [ ]
  obj.each {|elem|
    type=""
    value=""
    a = [ ]
    elem.each {|k,v|
      ifk == —Children
        b=extract(v)
        a. push(b)
      else
        type = vifk == —type
        value = vifk == —value
      end
    }
    a. prepend("#{type}:#{value}")
    ary<a
  }
  ary.flatten
end

defunion(ary)
  aary2 = [ ]
  aary3 = [ ]
  ary.each do|elem|
    ifelem.include?("h")
      if!ary2.empty?
        aary3.push(ary2)
        aary2 = [ ]
      end
      aary2.push(em)
    elsifelem.include?("p")
      aary2.push(em)
    end
  end
  aary3.push(ary2)
  aary3
end


2022-09-30 19:34

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.