Advertisement
obernardovieira

Floadting down from the sky (day 2) [SLiSW]

Jul 22nd, 2015
508
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Ruby 2.15 KB | None | 0 0
  1. #it's getting really hard :o
  2.  
  3. #read and write a file with and without blocks
  4.  
  5. #method with blocks
  6. filename = 'text.txt'
  7. #write
  8. File.open(filename,'w') {|file| file.write('ola ate logo')}
  9. #read
  10. File.open(filename,'r') {|file| puts file.read}
  11.  
  12.  
  13. #method without blocks
  14. filename = 'text.txt'
  15. #write
  16. file = File.open(filename,'w')
  17. file.write('ola')
  18. file.close
  19. #read
  20. file = File.open(filename,'r')
  21. puts file.read
  22. file.close
  23.  
  24.  
  25. #can I translate hash to array? And array to hash?
  26.  
  27. #hash to array
  28. array = []
  29. hash = { "a"=>["a", "b", "c"], "b"=>["b", "c"] }
  30. hash.each_key {|p| array.push(hash[p])}
  31. #array to hash
  32. array = [["a", "b", "c"], ["b", "c"]]
  33. hash = Hash[*array]
  34.  
  35.  
  36. #can I iterate through a hash ?
  37. hash.each_value {|p| puts "-> #{p}"}
  38.  
  39.  
  40. ##DO
  41. #Exercise 1
  42. #
  43. a = ['1','2','3','4','5','6','7','8','9','10','11','12','13','14','15','16']
  44. #
  45. a.each {|p| puts "-> #{p}"}
  46. #
  47. a.each_slice(4) {|p| puts "-> #{p}"}
  48.  
  49. #Exercise 2
  50. #Well, it's a little  more complicated, so I need to make an example first and then implement in the tree
  51. #So, based on this
  52. hs = {"grandpa" => {"dad" => {"child1" => {}, "child2" => {}}, "uncle" => {"child3" => {}, "child4" => {}}}}
  53. def readAll(tree = {})
  54.     puts "tree-> #{tree}"
  55.     nome = tree.keys[0]
  56.     child = tree[nome].collect {|i,m| readAll(i=>m)}
  57. end
  58.  
  59. readAll(hs)
  60. #I updated the tree
  61. class Tree
  62.   attr_accessor :children, :node_name
  63.  
  64.   def initialize(tree={})
  65.     @node_name = tree.keys[0]
  66.     @children = tree[node_name].collect {|i,m| Tree.new(i=>m)}
  67.   end
  68.  
  69.   def visit_all(&block)
  70.     visit &block
  71.     children.each {|c| c.visit_all &block}
  72.   end
  73.  
  74.   def visit(&block)
  75.     block.call self
  76.   end
  77.  
  78. end
  79.  
  80. ruby_tree = Tree.new( {"grandpa" => {"dad" => {"child1" => {}, "child2" => {}}, "uncle" => {"child3" => {}, "child4" => {}}}} )
  81.  
  82.  
  83. puts "visiting entire tree"
  84. ruby_tree.visit_all {|node| puts node.node_name}
  85.  
  86.  
  87. #Exercise 3
  88. #the file text.txt contains
  89. ola ate logo
  90. ja sei
  91. ainda nao sei
  92. #and the code is
  93. File.open('text.txt','r').each_with_index {|l,p| puts "-> #{l},#{p}" if l=~/sei(.*)/ }
  94. #you can also use readlines or each_line insted of each_with_index but you will not get the index of line
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement