info

書籍「7つの言語7つの世界」でRubyの章を読み飛ばそうと思ったけど、一部の問題だけ解く

配列をハッシュにしろ

[1,2,3].zip([[4, 5, 6],5,6]).inject(Hash::new){|x, y| x[y[0]] = y[1]; x}

配列が入れ子じゃなかったら

Hash[*[1,2,3].zip([4,5,6]).flatten]

16個と4個の配列を4個と1個づつで表示させろ
eachを使って

te = Array::new(16){|x| x}
fo = Array::new(4){|x| x}

fo.each.with_index {|x, y| p [fo[y], te[x*4..x*4+3]]} 

each_sliceを使って

te = Array::new(16){|x| x}
fo = Array::new(4){|x| x}
te.each_slice(4).with_index{|x, y| p [fo[y], x]}  

Treeクラスを改造して、ハッシュを木構造に変換

class Tree
  attr_accessor :name, :children

  def initialize(arg)
    if arg[:rootname].nil? then
      @name = arg[:hash].keys[0]
      if arg[:hash].values[0].empty? then                                                                                                 
        @children = []
      else
        @children = arg[:hash].values[0].map do |x, y|                                                                                    
          Tree::new rootname: x,  hash: y
        end
      end                                                                                                                                 

    else
      @name = arg[:rootname]
      if arg[:hash].empty? then
        @children = []
      else
        @children = arg[:hash].map do |x, y|
          Tree::new rootname: x,  hash: y
        end                                                                                                                               
      end
    end
  end

  def visit(&block)
    block.call self
  end

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

tree = Tree::new(hash: {grandpa: {dad: {child1: [], child2: []}, uncle: {child3: [], child4: []}}})

tree.visit_all{|x| p x.name}