Advertisement
ice09

7l7w ruby day2

Nov 2nd, 2011
418
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Ruby 1.16 KB | None | 0 0
  1. # Print the content of an array of sicteen numbers, four numbers at a time, using just each
  2. array = []
  3. (1..16).to_a.each { |item|
  4.   array << item
  5.   if (array.length == 4)
  6.     p ar
  7.     ar = []
  8.   end
  9. }
  10.  
  11. # Same with each_slice in Enumerable
  12. (1..16).to_a.each_slice(4) { |item| p item }
  13.  
  14. # 2. Change the UI of the Tree class to accept a hash for configuration
  15. #
  16. # Download Tree code here: http://pragprog.com/titles/btlang/source_code
  17. # Change to initialize method of the original code
  18.  
  19. def initialize(hash)
  20.   @children = []
  21.   hash.each_pair { |name, children|
  22.     @node_name = name
  23.     if !children.empty?
  24.       children.each_pair { |child_name, children_nodes|
  25.         new_hash = {child_name => children_nodes}
  26.         @children << Tree.new(new_hash)
  27.       }
  28.     end
  29.   }
  30. end
  31.  
  32. # ...and call of the new UI :)
  33.  
  34. ruby_tree = Tree.new({'grandpa' => { 'dad' => {'child 1' => {}, 'child 2' => {} }, 'uncle' => {'child 3' => {}, 'child 4' => {}}}})
  35.  
  36. # 3. Grep the lines of a file matching a simple regular expression (/tree/) with line number
  37.  
  38. File.open("tree.rb").each_with_index { |line, index|
  39.   if line =~ /tree/
  40.     p "##{index+1} #{line}"  
  41.   end  
  42. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement