Monday, February 18, 2013

7 Languages in 7 weeks: Ruby day 2


Day 2: Floating Down from the sky


On day 2 we're introduced to code blocks, arrays, hashes and mixins. The more I see code blocks in other languages the more I am looking forward to Java 8. Coming from Java I get particulary jealous of languages with syntaxctic sugar for arrays and hashes; initialising them in Java is cumbersome.

Self-Study

1) Print the contents of an array 4 elements at a time:

Sticking to the verbose solution for now:


array = Array(1..16)

array.each do |x|
  if (x % 4 == 0) 
    print "#{x}\n"
  else
    print "#{x},"
  end
end

Now with slice:

irb(main):014:0> array = Array(1..16)
=> [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16]
irb(main):015:0> array.each_slice(4) {  |slice| puts slice.join(",") }
1,2,3,4
5,6,7,8
9,10,11,12
13,14,15,16

2) Tree with a nice constructor:

After finishing this I found a nicer solution with collect, but here is my original:

class Tree
  attr_accessor :children, :node_name

  def initialize( fullTree={})
    @children = []
    @node_name = fullTree.keys.first
    fullTree[@node_name].each do |key,value| 
      children.push(Tree.new( {key=>value} ))
    end
  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({ 'grandad' => { 'dad' => { 'child 1' => {}   }, 'uncle'   => {}  } })

ruby_tree.visit_all { |t| puts t.node_name  }

3) Ruby grep!

pattern = Regexp.new(ARGV[0])
file = File.new(ARGV[1], "r")

counter = 0
file.each_line do |line|
  if line.match(pattern)
    puts "#{counter}: #{line}"
  end
  counter = counter + 1
end

Day 3 to come some time this week hopefully!

1 comment:

P said...

Doesn't work with
array = Array(11..26)

11,12
13,14,15,16
17,18,19,20
21,22,23,24
25,26,[Finished in 0.2s]

Your solution is based on elements, not indexes.

Liked your talk at DevoxxPL