From adccaf0c539bbcafb5654af5d604738622857757 Mon Sep 17 00:00:00 2001 From: Jason Staten Date: Sat, 5 Oct 2019 14:43:47 -0600 Subject: [PATCH] day2 --- ruby/day2.rb | 116 +++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 116 insertions(+) create mode 100644 ruby/day2.rb diff --git a/ruby/day2.rb b/ruby/day2.rb new file mode 100644 index 0000000..22632aa --- /dev/null +++ b/ruby/day2.rb @@ -0,0 +1,116 @@ +require 'minitest/autorun' + +class Tree + include Enumerable + + 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 + + alias :each :visit_all + def visit(&block) + block.call self + end + + def self.build(hash) + hash.map {|name, children| + Tree.new(name, self.build(children)) + } + end +end + +class Hash + def to_tree + end +end + +describe 'day 2' do + it 'opens files' do + File.open 'README.md' do |file| + # This will close when done + expect(file.each_line.first).wont_be_nil + end + end + + it 'converts hashes to arrays' do + person = {name: 'Alice', age: 42, country: 'US'} + expect(person.to_a).must_equal [ + [:name, 'Alice'], + [:age, 42], + [:country, 'US'], + ] + end + + it 'converts arrays to hashes' do + car = [[:make, 'Ford'], [:model, 'Pinto'], [:top_speed, 35]] + expect(car.to_h).must_equal ({ + make: 'Ford', + model: 'Pinto', + top_speed: 35, + }) + end + + it 'iterates through hashes' do + pokemon = {name: 'Pikachu', type: 'Electric', weight: 13.2} + pokemon.each do |key, value| + expect(pokemon[key]).must_equal value + end + end + + it 'has stack-like arrays' do + stack = [] + stack << 1 << 2 << 3 + expect(stack.pop).must_equal 3 + expect(stack.pop).must_equal 2 + expect(stack.pop).must_equal 1 + end + + it 'has queue-like arrays' do + stack = [] + stack << 1 << 2 << 3 + expect(stack.shift).must_equal 1 + expect(stack.shift).must_equal 2 + expect(stack.shift).must_equal 3 + end + + it 'has lookup arrays' do + lookup = [] + lookup << [:yogurt, :dairy] << [:carrot, :veggie] << [:tomato, :fruit] + expect(lookup.assoc(:yogurt)).must_equal [:yogurt, :dairy] + expect(lookup.assoc(:tomato)).must_equal [:tomato, :fruit] + lookup.unshift [:tomato, :veggie] + expect(lookup.assoc(:tomato)).must_equal [:tomato, :veggie] + end + + it 'handles contents of 16 numbers' do + numbers = (0...16).to_a + numbers.each_slice(4) do |nums| + expect(nums.length).must_equal 4 + end + end + + it 'makes a tree' do + + tree = Tree.build( + 'grandpa' => { + 'dad' => { + 'child 1' => {}, + 'child 2' => {} + }, + 'uncle' => { + 'child 3' => {}, + 'child 4' => {} + } + } + ).first + + expect(tree.map &:node_name).must_equal ['grandpa', 'dad', 'child 1', 'child 2', 'uncle', 'child 3', 'child 4'] + end + + +end