Tuesday, December 9, 2014

7L7W Week 1: Ruby Day 2>A spoonful of sugar

I feel like I must be missing something. Because this:
class Tree
  attr_accessor :children, :node_name
  def initialize(name, children=[])
    if children != []
      @node_name = name
    elsif name.is_a?(Hash)
      @node_name = name.keys[0]
      name[@node_name].each {|trunk|
        children << Tree.new(trunk)
        }
    elsif name.is_a?(Array)
      @node_name = name[0]
      name[1].each {|trunk|
        children << Tree.new(trunk)
        }
    end
    @children = children
  end
  
  def visit_all(&block)
    visit &block
    children.each {|c| c.visit_all &block}
  end
  
  def visit(&block)
    block.call self
  end
end

looks ridiculous. The main problem seems to be that name[@node_name].each is giving me arrays instead of hashes. Which means I have to account for another type that I can't readily predict in advance... which seems to end up being the bane of dynamically typed languages. Yesyesyes ducktyping, &etc. I can't access elements in a hash the same way I access elements in an array so that's not really applicable here.

On the other hand,
i=0
File.open("data.txt", 'r') do |file|
  file.each do |line|
    i += 1
    puts "#{i} #{line}" if /dialog/ =~ line
  end
end
puts "----------------------------"
puts "Searched #{i} lines of file."

was relatively easy. Except for the false start with File.foreach which didn't seem to actually be giving me full lines from the file. Looked like it was giving me strings the size of some internal read buffer. Frankly, I expect enumerating a file to give me each line. Maybe it was user error.

Still. I'm not particularly impressed with Ruby. It feels a lot like working in PHP 8 years ago. Only with anonymous functions. Day3 is subtitled 'Serious Change' so maybe that'll be interesting.

No comments: